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

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