Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* 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 || !head->next)
return NULL;
//p1 is our slow pointer and p2 is our fast pointer
ListNode *p1=head;
ListNode *p2=head;
while(p1 && p2 && p2->next)
{
p1=p1->next;
p2=p2->next->next;
//we are stuck in a loop
if(p1==p2)
{
//finding tail of the loop
p1=head;
while(p1!=p2)
{
p1=p1->next;
p2=p2->next;
}
return p1;
}
}
//if there is no loop return null
return NULL;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment