Write a simple code to identify given LinkedList has a loop and if loop is present then
calculate the lenght of a loop. Length of a loop is count of nodes with in the loop. If loop is not present
then it should return 0.
The loop count is 5 in the below image.
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.
The common point is one of the loop node. Here is our approach:
- We store the reference of the common point in a temporary variable.
- Initialize a counter with 1.
- Start iterating to next node from the common point and increment the counter till we again reach the common point.
- At that point, the counter value will be equal to the length of the loop.
|