环形链表Ⅱ-力扣

第一种解法时哈希表,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;
    }
};
相关推荐
yuuki23323315 分钟前
【数据结构】用顺序表实现通讯录
c语言·数据结构·后端
夏鹏今天学习了吗44 分钟前
【LeetCode热题100(59/100)】分割回文串
算法·leetcode·深度优先
还是码字踏实1 小时前
基础数据结构之数组的双指针技巧之对撞指针(两端向中间):三数之和(LeetCode 15 中等题)
数据结构·算法·leetcode·双指针·对撞指针
轮到我狗叫了4 小时前
力扣.84柱状图中最大矩形 力扣.134加油站牛客.abb(hard 动态规划+哈希表)牛客.哈夫曼编码
算法·leetcode·职场和发展
抠脚学代码5 小时前
Linux开发-->驱动开发-->字符设备驱动框架
linux·数据结构·驱动开发
熬了夜的程序员6 小时前
【LeetCode】99. 恢复二叉搜索树
算法·leetcode·职场和发展
Kent_J_Truman6 小时前
LeetCode Hot100 自用
算法·leetcode·职场和发展
还是码字踏实6 小时前
算法题种类与解题思路全面指南:基于LeetCode Hot 100与牛客Top 101
算法·leetcode
星释8 小时前
Rust 练习册 8:链表实现与所有权管理
开发语言·链表·rust
熬了夜的程序员8 小时前
【LeetCode】101. 对称二叉树
算法·leetcode·链表·职场和发展·矩阵