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走过的距离:a+b,fast走过的距离:a+b+c+b。
因为fast的速度是slow的两倍,所以fast走的距离是slow的两倍,有 2(a+b) = a+b+c+b,可以得到a=c(这个结论很重要!)。
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* dummy=new ListNode(-1);
dummy->next=head;
ListNode *slow=dummy, *fast=dummy;
bool flag=false;
while(fast && fast->next){
slow=slow->next;
fast=fast->next->next;
if(fast==slow) { flag=true; break; }
}
if(!flag) return NULL;
ListNode* result=dummy;
while(result != slow){
result=result->next;
slow=slow->next;**strong text**
}
return result;
}
};