0
点赞
收藏
分享

微信扫一扫

141. 环形链表———附带详细代码和思路

醉东枫 2022-03-23 阅读 35

文章目录

1 题目

在这里插入图片描述

2 思路

2.1 思路一

使用哈希表存储每次遍历后的指针的地址,遍历链表,如果遍历结束前,发现哈希表中已存在目前遍历的指针地址,就返回false,否则返回true。

2.2 思路二

摘自官网解说
在这里插入图片描述

3 代码

3.1 代码1

class Solution {
public:
    bool hasCycle(ListNode *head) {
        unordered_set<ListNode*> seen;
        while(head != nullptr){
           if(seen.count(head) > 0){
               return true;
           }else{
               seen.insert(head);
           }
           head = head->next;
        }
        return false;
    }
};

3.2 代码2

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head == nullptr || head->next == nullptr){
            return false;
        }
        ListNode *slow = head, *fast = head->next;
        while(slow != fast){
            if(fast == nullptr || fast->next == nullptr){
                return false;
            }
            fast = fast->next->next;
            slow = slow->next;
        }
        return true;
    }
};
举报

相关推荐

0 条评论