141.环形链表 & 142.环形链表II

141.环形链表 & 142.环形链表II

141.环形链表

思路:快慢指针 or 哈希表

快慢指针代码:

cpp 复制代码
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head==nullptr||head->next==nullptr)
        return false;
        ListNode *fast=head->next; //不能设置成head,否则不进入while循环
        ListNode *slow=head;
        while(fast!=slow){
            //如果无环fast在slow前面,只需要判断fast
            if(fast->next!=nullptr&&fast->next->next!=nullptr){
                fast=fast->next->next;
                slow=slow->next;
            }else{  //无环
                return false;
            }
        }
        return true;
    }
};

哈希表代码:

cpp 复制代码
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        unordered_set<ListNode*> hash;
        ListNode* cur=head;
        while(cur!=nullptr){
            //哈希表中出现过
            if(hash.count(cur)){
                return cur;
            }
            hash.insert(cur);
            cur=cur->next;
        }
        return nullptr;
    }
};

142.环形链表II

思路:快慢指针+数学推导 or 哈希表

哈希表同前,数学推导见下图,

代码:

cpp 复制代码
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode *slow = head, *fast = head;
        while (fast != nullptr) {
            slow = slow->next;
            if (fast->next == nullptr) {
                return nullptr;
            }
            fast = fast->next->next;
            if (fast == slow) {
                ListNode *ptr = head;
                while (ptr != slow) {
                    ptr = ptr->next;
                    slow = slow->next;
                }
                return ptr;
            }
        }
        return nullptr;
    }
};
相关推荐
郝学胜-神的一滴4 小时前
深入解析Python字典的继承关系:从abc模块看设计之美
网络·数据结构·python·程序人生
不知名XL10 小时前
day50 单调栈
数据结构·算法·leetcode
cpp_250112 小时前
P10570 [JRKSJ R8] 网球
数据结构·c++·算法·题解
cpp_250112 小时前
P8377 [PFOI Round1] 暴龙的火锅
数据结构·c++·算法·题解·洛谷
TracyCoder12313 小时前
LeetCode Hot100(26/100)——24. 两两交换链表中的节点
leetcode·链表
季明洵13 小时前
C语言实现单链表
c语言·开发语言·数据结构·算法·链表
only-qi13 小时前
leetcode19. 删除链表的倒数第N个节点
数据结构·链表
cpp_250113 小时前
P9586 「MXOI Round 2」游戏
数据结构·c++·算法·题解·洛谷
浅念-13 小时前
C语言编译与链接全流程:从源码到可执行程序的幕后之旅
c语言·开发语言·数据结构·经验分享·笔记·学习·算法
爱吃生蚝的于勒13 小时前
【Linux】进程信号之捕捉(三)
linux·运维·服务器·c语言·数据结构·c++·学习