What's the best (halting) algorithm for determining if a linked list has a cycle in it?
[Edit] Analysis of asymptotic complexity for both time and space would be sweet so answers can be compared better.
[Edit] Original question was not addressing nodes with outdegree > 1, but there's some talk about it. That question is more along the lines of "Best algorithm to detect cycles in a directed graph".
A linked list contains a cycle if it consists of a node that can be reached again by continuously following the next pointer. Explanation: The linked list consists of a loop, where the last node connects to the second node.
A simple solution is to use hashing. The idea is to traverse the given list and insert each encountered node into a set. If the current node already presents in the set (i.e., it is seen before), that means a cycle is present in the list.
We have used Floyd's cycle finding algorithm to check if there is a loop in LinkedList . Notice the code inside the checkLoop() method. Here, we have two variables named first and second that traverse the nodes in LinkedList . Two nodes are traversing at different speeds.
Have two pointers iterating through the list; make one iterate through at twice the speed of the other, and compare their positions at each step. Off the top of my head, something like:
node* tortoise(begin), * hare(begin); while(hare = hare->next) { if(hare == tortoise) { throw std::logic_error("There's a cycle"); } hare = hare->next; if(hare == tortoise) { throw std::logic_error("There's a cycle"); } tortoise = tortoise->next; }
O(n), which is as good as you can get.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With