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?
IDEA
借用別人的一個圖來說明。
設置兩個指針,slow每次走一步,fast每次走兩步
X爲鏈表投,Y爲環的起點,Z爲兩個指針相遇位置
a爲從頭到環起點的距離,b+c等於環長l
則有: 2(a+b)=a+b+n(b+c)
=> a=(n-1)b+nc=(n-1)(b+c)+c=(n-1)l+c
即讓一個指針在X,一個指針在Z點(兩個指針速度相同),第一個指針走a距離,等於第二個指針走過c加(n-1)個環長,最終早Y點相遇,即環的起點
CODE
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head==NULL)
return NULL;
ListNode *slow=head,*fast=head;
while(fast&&fast->next){
slow=slow->next;
fast=fast->next->next;
if(slow==fast){
slow=head;
while(slow!=fast){
slow=slow->next;
fast=fast->next;
}
return fast;
}
}
return NULL;
}
};