/*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()
p1=p2=firstNode; //Start with the first loop
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
return true; //p1 and p2 met, so this means that there is a cycle
//This means that p2 could not move forward
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).