Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
思路一:
先用快慢指针确认是否存在环,如果存在,将慢指针指回链表头,快指针不动,快慢指针同步一次向后走一步,再次相遇的节点便是环开始的节点。
证明过程如下:
假设S,F两个指针首次相遇在Z点,SL, SF分别为两个指针走过的距离,则
SL = a + b
SF = a + b + nL (L 为环的周长)
=> 2(a + b) = a + b + nL
a + b = nL
a = nL - b = (n - 1)L + L - b = (n - 1) L + c
因为a + b > 0,所以nL > 0, n > 0, n >= 1 推出 n - 1 >= 0
所以,a的长度为c 加上 ML (M > 0)
就是当SLOW重新从原点出发,而FAST继续走时,当SLOW走到Y点,FAST也会绕N圈后再走C长度到达Y点,
两个点正好会在Y点相遇。
得证。
参考:http://www.cnblogs.com/yuzhangcmu/p/4155676.html
1 public ListNode detectCycle(ListNode head) { 2 if(head == null || head.next == null) { 3 return null; 4 } 5 ListNode slow = head; 6 ListNode fast = head; 7 while(fast != null && fast.next != null) { 8 slow = slow.next; 9 fast = fast.next.next; 10 if(slow == fast) { 11 slow = head; 12 while(true) { 13 if(slow == fast) { 14 return slow; 15 } 16 slow = slow.next; 17 fast = fast.next; 18 } 19 } 20 } 21 return null; 22 }