Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine whether a linked list contains a loop? [duplicate]

Tags:

linked-list

Possible Duplicates:
find whether a loop in a linked list without two pointers
How to determine if a linked list has a cycle using only two memory locations.
Best algorithm to test if a linked list has a cycle

During a preparation for a job interview, I encountered the following question:

How can you determine whether a linked list (of any type) contains a loop, using additional space complexity of O(1)? You cannot assume that the loop starts at the first node (and of course, the loop doesn't have to contain all nodes).

I couldn't find the answer, though I have the feeling it's quite simple...

like image 834
ET. Avatar asked Jun 08 '10 22:06

ET.


People also ask

How do you check if a linked list is looped?

How do you detect a loop in a linked list? A loop can be detected efficiently using the fast and slow pointer algorithm, where the fast pointer moves by two nodes and the slow pointer move by one node at a time.

What is the optimal way to detect a loop in a double linked list?

Detect Loop using Floyd's Cycle detection algorithm and get the pointer to a loop node. Count the number of nodes in the loop. Let the count be k. Fix one pointer to the head and another to a kth node from the head.

Which can test the presence of a loop in a linked list?

You can make use of Floyd's cycle-finding algorithm, also known as tortoise and hare algorithm. The idea is to have two references to the list and move them at different speeds. Move one forward by 1 node and the other by 2 nodes. If the linked list has a loop they will definitely meet.

How do you find a linked list contains a cycle?

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.


1 Answers

Easy. Maintain two pointers into the list. At each step, advance one pointer by a single link, and advance the other by two links. Test to see if they point to the same element. If so, you have a loop. If not, repeat until you find a loop or you reach the end of the list.

like image 108
dty Avatar answered Sep 28 '22 08:09

dty