【Leetcode142】Linked List Cycle II

Pointer speed, slow down the pointer when d + s1, the pointer quickly go d + s1 + s2 + s1 exactly coincide with full pointer, wherein s1 + s2 is perimeter,

In this case the total distance is just fast slow pointer pointer twice, namely:

d+s1+s2+s1 = 2×(d+s1)

s2 = d

I.e., while starting from the meeting point and the first, bound in the annulus meet. 

/**
 * 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) {
        ListNode* n1 = head;
        ListNode* n2 = head;
        bool flag = false;
        while(n2 && n2->next){
            n1 = n1->next;
            n2 = n2->next->next;
            if(n1 == n2){
                flag = true;
                break;
            }
        }
        if(!flag) return NULL;
        n1 = head;
        while(n1 != n2){
            n1 = n1->next;
            n2 = n2->next;
        }
        return n1;
    }
};

 

Published 112 original articles · won praise 15 · views 20000 +

Guess you like

Origin blog.csdn.net/weixin_39458342/article/details/104980849