LeetCode Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Follow up:

Can you solve it without using extra space?

找出有環鏈表的起點,首先判斷鏈表是否存在環,使用快指針(每次走兩步)、和慢指針(每次走一步),如果有環,兩個必然會相遇的。這個題目還要求找出鏈表環的起點
第一次相遇時
慢指針走過的路程S1 = 非環部分長度 + 弧A長
快指針走過的路程S2 = 非環部分長度 + n * 環長 + 弧A長
S1 * 2 = S2,可得 非環部分長度 = n * 環長 - 弧A長
讓指針A回到起始點後,走過一個非環部分長度,指針B走過了相等的長度,也就是n * 環長 - 弧A長,正好回到環的開頭。

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


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