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.
找到一個鏈表的環(huán)的起點(diǎn)雪位。
使用快慢指針的方法,先找到鏈表是否有環(huán)回窘;
在快慢指針重合的地方孵户,快指針正好比慢指針多走一個環(huán)的長度北戏;
假設(shè)鏈表非環(huán)一共有K個元素而咆,環(huán)有S個元素吮炕;
假設(shè)此時slow走了K+X步歧蒋,那此時fast比它多走一個環(huán)宁炫,走了K+X+S步偿曙;
由于快指針一次走兩步,(K+X+S)=2*(K+X)羔巢;
S=K+X望忆;
也就是說環(huán)上元素個數(shù)等于非環(huán)上元素個數(shù)加上slow已經(jīng)在環(huán)上走過的罩阵;
那么找兩個指針,同時從head和slow的位置往前走启摄,他們應(yīng)該在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;
};