Write a function findFirstLoopNode() that checks whether a given Linked List contains loop. If loop is present then it returns point to first node of loop. Else it returns NULL.
We have discussed Floyd’s loop detection algorithm. Below are steps to find first node of loop.
1. If a loop is found, initialize slow pointer to head, let fast pointer be at its position.
2. Move both slow and fast pointers one node at a time.
3. The point at which they meet is the start of the loop.
Loop starting node is 15
How does this approach work?
Let slow and fast meet at some point after Floyd’s Cycle finding algorithm. Below diagram shows the situation when cycle is found.
We can conclude below from above diagram
Distance traveled by fast pointer = 2 * (Distance traveled by slow pointer) (m + n*x + k) = 2*(m + n*y + k) Note that before meeting the point shown above, fast was moving at twice speed. x --> Number of complete cyclic rounds made by fast pointer before they meet first time y --> Number of complete cyclic rounds made by slow pointer before they meet first time
From above equation, we can conclude below
m + k = (x-2y)*n Which means m+k is a multiple of n.
So if we start moving both pointers again at same speed such that one pointer (say slow) begins from head node of linked list and other pointer (say fast) begins from meeting point. When slow pointer reaches beginning of loop (has made m steps), fast pointer would have made also moved m steps as they are now moving same pace. Since m+k is a multiple of n and fast starts from k, they would meet at the beginning. Can they meet before also? No because slow pointer enters the cycle first time after m steps.
- Find the middle of a given linked list in C and Java
- Program for n'th node from the end of a Linked List
- Write a function to get Nth node in a Linked List
- Given only a pointer/reference to a node to be deleted in a singly linked list, how do you delete it?
- Detect loop in a linked list
- Write a function to delete a Linked List
- Write a function that counts the number of times a given int occurs in a Linked List
- Reverse a linked list
- Given only a pointer to a node to be deleted in a singly linked list, how do you delete it?
- Write a function to get the intersection point of two Linked Lists.
- Function to check if a singly linked list is palindrome
- The Great Tree-List Recursion Problem.
- Clone a linked list with next and random pointer | Set 1
- Memory efficient doubly linked list
- Given a linked list which is sorted, how will you insert in sorted way
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.