【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;
    }
};
发布了112 篇原创文章 · 获赞 15 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_39458342/article/details/104980849