返回

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

发布时间:2023-02-03 13:46:03 187

1 题目

在这里插入图片描述

2 思路

2.1 思路一

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

2.2 思路二

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

3 代码

3.1 代码1

class Solution {
public:
    bool hasCycle(ListNode *head) {
        unordered_set 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)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线