环形链表Ⅱ-力扣

第一种解法时哈希表,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;
    }
};
相关推荐
D e re k ZH3 小时前
C++ 系统学习手记:从语法细节到工程实践
开发语言·数据结构·c++·算法
文丑颜不良啊6 小时前
LeetCode2261~2280题目解析
java·leetcode
zh_xuan9 小时前
LeeCode 496. 下一个更大元素I
数据结构·算法·栈·单调栈
文丑颜不良啊12 小时前
LeetCode2241~2260题目解析
java·leetcode
文丑颜不良啊12 小时前
LeetCode2321~2340题目解析
java·leetcode
白杨尚青13 小时前
C++进阶篇(五):红黑树——四条规则、三种插入情况与旋转变色
开发语言·数据结构·c++·stl·红黑树·平衡二叉树
likexuec1 天前
数据结构(2)
数据结构
文丑颜不良啊1 天前
LeetCode2221~2240题目解析
java·leetcode
Navigator_Z1 天前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
D e re k ZH1 天前
C++ 标准库算法全景指南
数据结构·c++·算法