
Find the cycle in a linked list, if any?
June 11, 2007There are a lot of solutions of the problem. I am going with a well known approach which is constant space O(1) and 0(n) space.
The idea is to take two pointers P1 and P2 which are initially pointed to the first element of the linked list (head in case of you maintain it). Now, P1 goes one node and P2 goes two nodes at a time. If there is a loop in linked list , they will meet somewhere inside the loop, otherwise they will reach to tail .
bool loopdetect( struct node *p){
struct node *p1=p;
struct node *p2=p;
while(p1 && p2 && p1->link && p2->link
&& p2->next->next)
{
p1=p1->link; //p1 goes one node at a time
p2=p2->link->link; //p2 goes two nodes at a time
if(p1==p2)
{
cout < < “Found Loop” << endl;
return true;
}
}
return false;
}
However, there are other solutions. The solution reminds me yet another problem of finding out the middle element of the linear linked list just in one scan of the list.
Other Solution possible is:
2-Start from the beginning of the list and keep on reversing the link
list as you traverse it eventually you will reach the start of the list
again if the loop exists.

give the optimised answer.If two pointers doesn’t meet whaty will happen?
how we will find the loop?
if the two pointers doesn’t meet, then there is no loop !!