Write a program to identify given linked list contains loop or not. If loop exists, then
remove the loop.
The below diagram illustrates linked list loop/cycle:

In our last example, we have used Floyd’s Cycle detection algorithm to terminate when fast and slow pointers meet at a common point.
We will use same approach to identify loop. Here is our approach.
- We will use Floyd’s Cycle detection algorithm to identify loop and get the pointer to loop node.
- Count number of nodes in the loop. Let the count be k.
- Fix one pointer to the head node and another pointer to Kth node from the head.
- Move both pointers at the same pace, they will meet at loop starting node.
- Get the pointer to the last node of the loop and assign NULL to next value of it.
|