Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
Follow up:
Can you solve it without using extra space?
分析:
串长a + n,其中n为循环,当a + b步的慢指针与快指针相遇时,快指针已经走过了k圈。
即a + b + k * n = 2 * (a+b),求a,得到a = k * n - b。
也就是X走a步,等于Z位置上的指针再走k圈,相遇于Y点。
/**
* 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) {
if(head==null||head.next==null){
return null;
}
ListNode slow=head;
ListNode fast=head;
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
if(slow==fast){
ListNode slow2=head;
while(slow2!=slow){
slow2=slow2.next;
slow=slow.next;
}
return slow;
}
}
return null;
}
}