Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linked list loop detection algorithm

I read some interview question online about how would you find if there's a loop in a linked list, and solution (Floyd's cycle-finding algorithm) is to have two pointers, one is 2x faster than the other, and check if they meet again.

My question is: Why can't I just keep one pointer fixed, just move the other pointer forward by 1 step each time?

like image 208
Derek Li Avatar asked Sep 13 '11 08:09

Derek Li


People also ask

How do you find a loop in a linked list?

Step 1: Move 'S' to the start of the list, but 'F' would remain point to node 3. Step 2: Move 'S' and 'F' forward one node at a time until they meet. Step 3: The node where they meet is the start of the loop. Let's visualize the above algorithm for more clarity.

How do you find a loop node in a linked list?

Write a function findFirstLoopNode() that checks whether a given Linked List contains a loop. If the loop is present then it returns point to the first node of the loop. Else it returns NULL.

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.

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

Method 2 (Better Solution) Let the count be k. Fix one pointer to the head and another to a kth node from the head. Move both pointers at the same pace, they will meet at the loop starting node. Get a pointer to the last node of the loop and make the next of it NULL.


2 Answers

Because maybe not the complete linkedList is within the loop.

For a linked list lasso detection algorithm, you need two pointers:

enter image description here

As long as the first pointer is where the cowboy is, no loop is detected. But if you move it stepwise forward, it will eventually enter the loop.


BTW, lasso is the terminus technicus from graph theory, cowboy isn't.

like image 61
DaveFar Avatar answered Sep 22 '22 10:09

DaveFar


Because the first (non-moving) pointer might not lie within the loop, so the pointers would never meet. (Remember that a loop may consist of only part of the list.)

like image 30
Paul R Avatar answered Sep 21 '22 10:09

Paul R