Explian Floyd Cycle finding algorithm for circular link list?

Questions by pbchaudhari   answers by pbchaudhari

Showing Answers 1 - 3 of 3 Answers

Simultaneously go through the list by ones (slow iterator) and by twos (fast iterator). If there is a loop the fast iterator will go around that loop twice as fast as the slow iterator. The fast iterator will lap the slow iterator within a single pass through the cycle. Detecting a loop is then just detecting that the slow iterator has been lapped by the fast iterator.

// Best solution function boolean hasLoop(Node startNode)
{   Node slowNode = Node fastNode1 = Node 
fastNode2 = startNode;   
while (slowNode && fastNode1 = fastNode2.next() && 
fastNode2 = fastNode1.next()){     
if (slowNode == fastNode1 || slowNode == fastNode2) return true;     
slowNode = slowNode.next();   }   return false; }

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions