AlgoMaster Logo

Linked List Cycle II

values=[1, 2, 3, 4, 5],cyclePos=2
1public ListNode detectCycle(ListNode head) {
2    ListNode slow = head;
3    ListNode fast = head;
4
5    // Phase 1: Detect cycle
6    while (fast != null && fast.next != null) {
7        slow = slow.next;
8        fast = fast.next.next;
9
10        if (slow == fast) {
11            // Phase 2: Find entry point
12            slow = head;
13            while (slow != fast) {
14                slow = slow.next;
15                fast = fast.next;
16            }
17            return slow;
18        }
19    }
20
21    return null;
22}
0 / 11
12345head