leetcode142_環形鏈表||

一. 參考 leetcode141_環形鏈表_雙指針 https://blog.csdn.net/qieyuan4083/article/details/104336903

二. 哈希表,第一個重複的即爲環的入口.時間O(n),空間O(n).

三. Floyd算法.第一階段,找到鏈表是否有環,有環的話再找到相遇節點.

/**
 * 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 || head->next==NULL) return NULL;
        ListNode* slow = head;
        ListNode* fast = head->next;
        while(slow!=fast) {
            if(fast==NULL || fast->next==NULL) return NULL;
            slow = slow->next;
            fast = fast->next->next;
        }
        //找到快慢指針相遇點即爲slow.
        slow = slow->next;
        //兩者相遇即爲入口點.
        while(slow!=head) {
            slow = slow->next;
            head = head->next;
        }
        return head;
    }
};

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