[LeetCode] 142. Linked List Cycle II 單鏈表中的環之二


 

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

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Note: Do not modify the linked list.

 

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2:

Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:

Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.

 

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

 

這個求單鏈表中的環的起始點是之前那個判斷單鏈表中是否有環的延伸,可參之前那道 Linked List Cycle。這里還是要設快慢指針,不過這次要記錄兩個指針相遇的位置,當兩個指針相遇了后,讓其中一個指針從鏈表頭開始,一步兩步,一步一步似爪牙,似魔鬼的步伐。。。哈哈,打住打住。。。此時再相遇的位置就是鏈表中環的起始位置,為啥是這樣呢,這里直接貼上熱心網友「飛鳥想飛」的解釋哈,因為快指針每次走2,慢指針每次走1,快指針走的距離是慢指針的兩倍。而快指針又比慢指針多走了一圈。所以 head 到環的起點+環的起點到他們相遇的點的距離 與 環一圈的距離相等。現在重新開始,head 運行到環起點 和 相遇點到環起點 的距離也是相等的,相當於他們同時減掉了 環的起點到他們相遇的點的距離。代碼如下:

 

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode *slow = head, *fast = head;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) break;
        }
        if (!fast || !fast->next) return NULL;
        slow = head;
        while (slow != fast) {
            slow = slow->next;
            fast = fast->next;
        }
        return fast;
    }
};

 

討論:單鏈表中的環的問題還有許多擴展,比如求環的長度,或者是如何解除環等等,可參見網上大神的這個總結貼

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/142

 

類似題目:

Linked List Cycle

Find the Duplicate Number

 

參考資料:

https://leetcode.com/problems/linked-list-cycle-ii/

https://leetcode.com/problems/linked-list-cycle-ii/discuss/44793/O(n)-solution-by-using-two-pointers-without-change-anything

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM