Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best algorithm to test if a linked list has a cycle

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".

like image 646
cdleary Avatar asked Aug 29 '08 09:08

cdleary


People also ask

How do you know if a linked list has a cycle?

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.

What is the best way to detect a cycle in a linked list?

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.

How do I find a loop in a linked 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.


1 Answers

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.

like image 179
DrPizza Avatar answered Sep 21 '22 19:09

DrPizza