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.
找到一個鏈表的環的起點。
使用快慢指針的方法,先找到鏈表是否有環;
在快慢指針重合的地方,快指針正好比慢指針多走一個環的長度;
假設鏈表非環一共有K個元素,環有S個元素;
假設此時slow走了K+X步,那此時fast比它多走一個環,走了K+X+S步;
由于快指針一次走兩步,(K+X+S)=2*(K+X);
S=K+X;
也就是說環上元素個數等于非環上元素個數加上slow已經在環上走過的;
那么找兩個指針,同時從head和slow的位置往前走,他們應該在K步后會相遇,這就是我們要的元素。
var detectCycle = function(head) {
var slow = head, fast = head;
while(fast !== null && fast.next !== null) {
fast = fast.next.next;
slow = slow.next;
if (slow === fast) {
while (head !== slow) {
head = head.next;
slow = slow.next;
}
return slow;
}
}
return null;
};