牛客题霸NC3链表中环的入口节点Java题解

牛客题霸NC3链表中环的入口节点Java题解

https://www.nowcoder.com/practice/6e630519bf86480296d0f1c868d425ad?tpId=117&&tqId=34924&rp=1&ru=/ta/job-code-high&qru=/ta/job-code-high/question-ranking

方法:快慢指针
解题思路:利用快慢指针,快指针每次走2步,慢指针每次走1步,当快指针和慢指针相遇时,再让一个新的慢指针从起点出发(此时,原慢指针在和快指针的相遇点),让新慢指针和原慢指针同时出发,这样,当新慢指针和原慢指针再次相遇时,就i是链表中环的入口节点。

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
   public ListNode detectCycle(ListNode head){
        ListNode slow = head;
        ListNode fast = head;
 
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
 
            if(fast == slow){               //利用快慢指针找相遇点
                ListNode newSlow = head;    //新慢指针从起始位置出发
                while(newSlow != slow){     //新旧慢指针相遇时就是环的入口节点位置
                    slow  = slow.next;
                    newSlow = newSlow.next;
                }
                return slow;
            }
        }
        return null;
    }
}

 

posted @ 2020-11-27 11:33  云飞扬°  阅读(94)  评论(0编辑  收藏  举报