null
. Follow up:
Can you solve it without using extra space?
Draw a picture and visualize it:
11111222
222
Let's say x is the distance from head of the linked list to the entry node where the cycle begins, a is the distance from entry node where the cycle begins to the node where the slow and fast pointers meet, r is the size of the loop. s is the distance where slow pointer has travelled before slow point and fast pointer have met. L is the length from meet point to entry point.
2*s=s+nr;
s = nr;
x+a=nr=(n-1)*r + r = (n-1)*r + L-x;
x=(n-1)*r + L-x-a;
/**
* 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||head->next==NULL)
return NULL;
ListNode *p1=head;
ListNode *p2=head;
while(p1!=NULL&&p2!=NULL)
{
p1=p1->next;
p2=p2->next==NULL?NULL:p2->next->next;
if (p1==p2)
{
p2=head;
while(p1!=p2)
{
p1=p1->next;
p2=p2->next;
}
return p1;
}
}
return NULL;
}
};
No comments:
Post a Comment