【Leetcode142】Linked List Cycle II

快慢指針,慢指針走了d+s1的時候,快指針走了d+s1+s2+s1正好跟滿指針重合,其中s1+s2就是周長,

此時快指針的總路程正好也是慢指針的2倍,即:

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

s2 = d

即從起點和第一次相遇點同時出發,必然在入環處相遇。 

/**
 * 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;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章