If you represent a list by a pointer to its first node (list)
The algorithm to detect loops is described as follows:
- Declare two pointers (pFast) and (pSlow).
- Make pSlow and pFast point to list.
- Until (pSlow), (pFast) or both point to NULL:
- If , then STOP as a loop has just been found.
- If this point has been reached (one or both two pointers are NULL) then there are no loops in the list.
Lets assume that this algorithm is correct.
In this scheme, a loop situation is represented by the following diagram:
Note how every node, except the one pointing to the begining of a loop, is labeled with the number of its target minus one. So, if one node is labeled with i and it is not the begining of a loop, then it is pointed as next element by the node labeled with i-1.
The algorithm explained above can be described as a loop since its main step (3) is a set of sub-steps which repeated until the exit condition is satisfied. That forces us to represent pFast and pSlow in function of the iteration number in the algorithm execution (t).
If the list hadn’t have loops, pointers positions would be described in function of t as:
However there is a node where the loop starts and that function stops describing the evolution of the pointers. Assuming that this pointer is tagged with m, that the loop contains nodes (that is and ), and setting t=0 as iteration value when then:
If one pointer is indeed enough to detect loops using the algorithm described, then it must exist at least a solution to the equation .
This equation is true if and only if there is a value for t that makes:
This ends in a function, which generates values of t that are valid solutions to the equation described above:
Thus It is proved that one slow pointer and one fast pointer are enough to detect loop conditions in a linked list.