Possible Duplicate:
How to determine if a linked list has a cycle using only two memory locations.
hello i have been asked in an interview that how can i find a loop exists in a link list using only two pointers.
i have done the following:
1) find the center of the link list each time
2) by iterating this at the end both the pointers will be pointing the same node if not pointing the same node and finds a null then there is no loop in link list.
is there any efficient method to do this…?
thanx in advance.
I think you’re looking for Floyd’s cycle detection algorithm, also known as the “Tortoise and Hare algorithm”. The idea is to set one pointer (the “tortoise”) to the
first node in the list, and another pointer (the “hare”) to the next item. Then in
each step, the “tortoise” pointer is advanced one position, and the “hare” is advanced two steps. After each iteration, the pointers are checked to see whether they point to
the same node. If this ever occurs, that node must be part of a cycle.
To find the start of the cycle, one of the two pointers is repositioned to the
start of the list, while the other is left at its current position. Then both pointers
are advanced, this time by a single step per iteration for both pointers, until they meet again. This (second) meeting point is the first node in the cycle.