So I recently encountered the algorithm to determine whether a cycle exists in a linked list. The codes are as follows:
public boolean hasCycle(ListNode head) {
if (head == null) {
return false;
}
ListNode fast = head;
ListNode slow = head;
while (fast != null) {
if (fast.next == null) {
return false;
}
if (fast.next == slow) {
return true;
}
fast = fast.next.next;
slow = slow.next;
}
return false;
}
When trying to prove the correctness of this algorithm, I come up with an idea: Suppose the perimeter of the cycle is "a", the time elapsed before two pointers meet is "t". Since the speed of the "fast" node moves twice as fast as the "slow" node, we can get the mathematical relation:
2t mod a = t mod a
Now "a" is a constant represents perimeter, and "t" could be 1,2,3.... Then, how do I prove that no matter what value "a" is, we can always find a "t" such that the above equation is solvable?