题目:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
思路:
方法是利用两个指针从头开始,指针slow一次走一步,指针fast一次走两步,如果有环则两指针必定有重逢之时(这是Linked List Cycle里用到的)。
然后就是如何求出环的起始节点。
可以这么假定,从链的起点到环的起点,这段距离称为a。环的长度称为c,第一次相遇位置距环的起点距离为p。首先slow被fast追上时它一定没有走完整个环(想想为什么?)也就是说0<p<c.所以从出发到相遇,slow走过的距离为a+p,fast走过的距离为a+p+nc(n为正整数)。又因为p2速度为p1两倍,所以有2a+2p=a+p+nc,所以有a+p=nc。现在两指针均处在环起点过p的位置上,再走a个距离即可回到环的起点。而a恰好是链的起点到环的起点的距离,所以我们另其中一指针回到链的起点,另一指针仍在原地,同时以速度1前进,再次相遇一定是在环的起点了。
算法:
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head==null||head.next==null||head.next.next==null)
return null;
ListNode fast=head;
ListNode slow=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
if(fast==slow){
slow=head;
while(slow!=fast){
slow=slow.next;
fast=fast.next;
}
return slow;
}
}
return null;
}
}
参考:https://blog.youkuaiyun.com/monkeyduck/article/details/40083527