[LeetCode]linked-list-cycle ii 環形鏈表

問題描述

Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.

Follow up: Can you solve it without using extra space?

解題思路

首先,需要判斷鏈表中有無環,藉助快慢指針去尋找,fast每次走兩步,slow每次走一步,如果有環兩者一定會相遇。

然後,如果有環存在需要返回環的起點,這時把快慢指針中的一個指向head,另一個還在之前相遇的位置,然後兩指針以相同速度前進,下一次相遇的位置就是環的起點。

證明如下:

(鏈接:https://www.nowcoder.com/questionTerminal/6e630519bf86480296d0f1c868d425ad
來源:牛客網)

如下圖所示,X,Y,Z分別爲鏈表起始位置,環開始位置和兩指針相遇位置,則根據快指針速度爲慢指針速度的兩倍,可以得出:

2*(a + b) = a + b + n * (b + c);即

a=(n - 1) * b + n * c = (n - 1)(b + c) +c;

注意到b+c恰好爲環的長度,故可以推出,如將此時兩指針分別放在起始位置和相遇位置,並以相同速度前進,當一個指針走完距離a時,另一個指針恰好走出 繞環n-1圈加上c的距離。

故兩指針會在環開始位置相遇。

實現代碼

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

繼續學習鏈表~要多練多練呀

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