环形链表Ⅱ-力扣

第一种解法时哈希表,set在使用insert插入时,会返回一个pair,如果pair的值为0,则插入失败,那么返回这个插入失败的节点,就是入环的第一个节点,代码如下:

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        unordered_set<ListNode*> set;
        auto cur = head;
        while(cur != NULL){
            if(set.insert(cur).second){
                cur = cur->next;
            }else{
                return cur;
            }
        }
        return NULL;
    }
};

第二种快慢指针的写法,数学推导相当精妙,推到过程可以参考代码随想录-环形链表Ⅱ

参考代码:

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;
    }
};
相关推荐
切糕师学AI4 小时前
环形缓冲区(Ring Buffer / Circular Buffer)详解:原理、优势、应用与高性能实现
数据结构·环形缓冲区
WolfGang0073215 小时前
代码随想录算法训练营 Day50 | 图论 part08
数据结构·算法·图论
晚枫歌F7 小时前
最小堆定时器
数据结构·算法
嫩萝卜头儿8 小时前
2 - 复杂度收尾 + 链表经典OJ
数据结构·算法·链表·复杂度
玛丽莲茼蒿9 小时前
Leetcode hot100 每日温度【中等】
算法·leetcode·职场和发展
样例过了就是过了9 小时前
LeetCode热题100 分割等和子集
数据结构·c++·算法·leetcode·动态规划
木木_王9 小时前
嵌入式Linux学习 | 数据结构 (Day05) 栈与队列详解(原理 + C 语言实现 + 实战实验 + 易错点剖析)
linux·c语言·开发语言·数据结构·笔记·学习
北顾笙9809 小时前
day38-数据结构力扣
数据结构·算法·leetcode
m0_629494739 小时前
LeetCode 热题 100-----14.合并区间
数据结构·算法·leetcode
xin_nai10 小时前
LeetCode热题100(Java)(5)普通数组
算法·leetcode·职场和发展