[Leetcode] 77. Linked List Cycle II

題目

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

Note: Do not modify the linked list.

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

解題之法

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

分析

這個(gè)求單鏈表中的環(huán)的起始點(diǎn)是之前那個(gè)判斷單鏈表中是否有環(huán)的延伸, 還是要設(shè)快慢指針,不過這次要記錄兩個(gè)指針相遇的位置,當(dāng)兩個(gè)指針相遇了后,讓其一指針從鏈表頭開始,此時(shí)再相遇的位置就是鏈表中環(huán)的起始位置。

詳細(xì)證明見這篇博客
關(guān)于鏈表的拓展問題見這篇博客

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容