i was looking at 4.1 Test for cyclicity problem (find the origin of cycle in a linked list, if any).
it gives one solution, then the variant question goes:
Variant: The following program purports to compute the beginning of the cycle
without determining the length of the cycle; it has the benefit of being more succinct
than the code listed above. Is the program correct?
public static ListNode <Integer > hasCycle(ListNode <Integer > head) {
ListNode <Integer > fast = head , slow = head;
while (fast != null && fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) { // There is a cycle.
// Tries to find the start of the cycle.
slow = head;
// Both pointers advance at the same time.
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow; // slow is the start of cycle.
}
}
return null; // No cycle.
}
this seems to implement Floyd’s cycle-finding algorithm which doesn’t determine the length of cycle either. so i’m inclined to think this code actually works… possibly you’re asking this because it doesn’t handle edge cases correctly as is written (?), but isn’t the core algorithm still correct?
or maybe the answer to variant question really was, ‘yes, this code works too’…