Find loops in a linked list.

There are several algorithms floating on the net to detect a cycle/loop in a linked list. The following code detects cycle in a linked list in time O(N) and space O(1).


/*Algorithm : P2 is moving through the list twice as fast as P1.
If the list is circular, it will eventually get around P1 and meet */

public boolean hasCycle()
{
DoubleNode p1,p2;
p1=p2=firstNode; //Start with the first loop

try
{
while (p2 != null) //If p2 reaches end of linked list, no cycle exists
{
p1=p1.next; //Move to next
p2=p2.next.next; //Move to 2 steps next
if(p1==p2)
return true; //p1 and p2 met, so this means that there is a cycle
}
}
catch(NullPointerException npe)
{
//This means that p2 could not move forward
return false;
}

return false;
}

No comments: