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 length of loop in linked list
- Find the fractional (or n/k - th) node in linked list
- Find modular node in a linked list
- Find the largest node in Doubly linked list
- Find kth node from Middle towards Head of a Linked List
- Recursive Approach to find nth node from the end in the linked list
- Find the second last node of a linked list in single traversal
- Swap Kth node from beginning with Kth node from end in a Linked List
- Detect loop in a linked list
- Check linked list with a loop is palindrome or not
- Detect and Remove Loop in a Linked List
- Make a loop at k-th position in a linked list
- Squareroot(n)-th node in a Linked List
- Remove first node of the linked list
- Remove every k-th node of the linked list
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.