uacs2024

导航

leetcode141-环形链表

141. 环形链表

方法一:快慢指针,如果存在环,快指针总会追上慢指针的。如果不存在环,那么遇到NULL就会直接结束

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode *dummyHead = new ListNode;
        dummyHead->next=head;
        ListNode *slow=dummyHead;
        ListNode *fast=dummyHead;
        while(slow&&fast&&fast->next)
        {
            slow=slow->next;
            fast=fast->next->next;
            if(slow==fast)  return true;
        }
        return false;
    }
};

方法二:集合?哈希表?把遍历过的结点放入set,如果当前遍历的结点已经存在于set中,那么就说明有环

class Solution {
public:
    bool hasCycle(ListNode *head) {
        unordered_set<ListNode*> seen;
        while (head != nullptr) {
            if (seen.count(head)) {
                return true;
            }
            seen.insert(head);
            head = head->next;
        }
        return false;
    }
};
/*
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/linked-list-cycle/solution/huan-xing-lian-biao-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/

 

posted on 2022-09-14 17:46  ᶜʸᵃⁿ  阅读(9)  评论(0编辑  收藏  举报