For this problem, we have to do a little math deduction:
let L1 indicates the distance between start point and head; L2 indicates the distance between start point and meet point; C indicates the length of cycle;
For fast pointer, it goes L1 + n*C + L2 before meet with slow pointer. And for slow pointer, it goes L1 + L2. We know the speed relationship between slow and fast is that
fast=2∗slow
Thus we have
L1=n∗C−L2
Which gives us a conclusion:
the distance between head and start equals to the distance between meet point to start point along forward movement.
ListNode *detectCycle(ListNode *head) {
// write your code here
if(!head || !head->next) return NULL;
ListNode *fast = head;
ListNode *slow = head;
ListNode *start = head;
while(fast->next && fast->next->next){
fast = fast->next->next;
slow = slow->next;
if(fast == slow){
while (slow != start){
slow = slow->next;
start = start->next;
}
return start;
}
}
return NULL;
}