How would you find a cycle in a linked list?

Answer Posted / sujith

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.

This solution is "Floyd's Cycle-Finding Algorithm" as
published in "Non-deterministic Algorithms" by Robert W.
Floyd in 1967. It is also called "The Tortoise and the Hare
Algorithm"

Is This Answer Correct ?    11 Yes 2 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is a program?

650


What is wrong in this statement?

597


What is the package for freshers(Non IIT) in amazon(hyderabad). And what is the same for those who are a contract employee.

3724


Explain a pre-processor and its advantages.

615


How can you restore a redirected standard stream?

604






What is a far pointer in c?

590


What is double pointer in c?

581


How can you draw circles in C?

615


There seem to be a few missing operators ..

611


explain what are actual arguments?

628


Differentiate between null and void pointers.

625


When c language was developed?

630


What is the right type to use for boolean values in c?

576


please send me the code for multiplying sparse matrix using c

1715


Is c++ based on c?

642