142. Linked List Cycle II - cocoder39/coco39_LC GitHub Wiki

142. Linked List Cycle II

head to meet pointing is d1, length of cycle is r, then 2d1 = d1 + nr. Thus d1 = n * r. head to entry of cycle is d2, then 2d1 + d2 is the total distance fast goes, since 2d1 + d2 = n * r + d2, fast and slow meets at entry of cycle

ListNode *detectCycle(ListNode *head) {
        ListNode* fast = head;
        ListNode* slow = head;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
            if (fast == slow) {
                slow = head;
                while (slow != fast) {
                    slow = slow->next;
                    fast = fast->next;
                }
                return slow;
            }
        }
        return nullptr;
    }