142环形链表

最简单的思路:哈希。进阶那个快慢指针确实想不到。

//哈希,空间为O(n)
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        unordered_set<ListNode*> adds ; 

        if(head == nullptr)
            return NULL;

        ListNode* cur = head;

        while(cur->next != nullptr)
        {
             if(adds.count(cur))
               return cur;
			   
             adds.insert(cur);
             cur = cur->next;

        }       
        return NULL;

    }
};
//使用快慢指针 空间为O(1)
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
    ListNode* fast = head;
    ListNode* slow = head;

    while(fast != nullptr && fast->next != nullptr)
    {
        fast = fast->next->next;
        slow = slow->next;
        if( fast == slow )
        {
            ListNode* index1 = head;
            ListNode* index2 = fast;
            while(index1 != index2)
            {
                index1 = index1->next;
                index2 = index2->next;
            }
            return index1;
        }
    }
    return NULL;
    }
};
posted @ 2025-01-06 21:38  名字好难想zzz  阅读(6)  评论(0)    收藏  举报