Recently i came across an interesting problem on "how to detect cycles in a linked list?". Digging into that i figured out this famous algorithm Flyod's cycle detection algorithm(aka Tortoise and Hare algorithm) on how to detect whether a linked list is cyclic.
What is a cycle?
Sample cycle
How to detect this cycle?
Code for the algorithm
public boolean hasCycle(Node first) {
if(first == null) // list does not exist..so no loop either.
return false;
Node tortoise, hare; // create two references.
tortoise = hare = first; // make both refer to the start of the list.
while(true) {
tortoise = tortoise.next; // 1 hop.
if(hare.next != null)
hare = hare.next.next; // 2 hops.
else
return false; // next node null => no loop.
if(tortoise == null || hare == null) // if either hits null..no loop.
return false;
if(tortoise.equals(hare)) // if the two ever meet...we must have a loop.{
{
return true;
}
}
}