Jack Li's Blog

0142. Linked List Cycle II

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        // fast move 2 pos
        // slow move 1 pos
        // pos count: 2(x+y) = x + y + n(y + z)
        // n = 1, x = z

        ListNode* fast = head;
        ListNode* slow = head;

        while(fast != nullptr && fast->next != nullptr) {
            fast = fast->next->next;
            slow = slow->next;

            // Encounter point find
            if(fast == slow) {
                slow = head;
                
                // fast starts from encouter ponit
                // slow starts from head
                // move together
                while(fast != slow) {
                    fast = fast->next;
                    slow = slow->next;
                }

                // return new encounter point
                return fast;
            }
        }

        return nullptr;
    }
};