leetcode 142. Linked List Cycle II

题目描述

哈希表解法

这个方法很容易想到,但需要O(N)的空间。

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*> hash_table;
        ListNode* cur = head;
        while(cur){
            if(hash_table.contains(cur))
                return cur;
            hash_table.insert(cur);
            cur = cur->next;
        }
        return nullptr;
    }
};

双指针法

判断是否有环只需要快慢指针就可以。要确定环的位置,还需要考虑数量关系。具体推导见LeetCode官方题解。

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) {
        if(head == nullptr || head->next == nullptr)
            return nullptr;
        ListNode* fast = head;
        ListNode* slow = head;
        while(fast->next && fast->next->next){
            fast = fast->next->next;
            slow = slow->next;
            if(fast==slow){
                ListNode* p1 = fast;
                ListNode* p2 = head;
                while(p1!=p2){
                    p1 = p1->next;
                    p2 = p2->next;
                }
                return p1;
            }
        }
        return nullptr;
    }
};
相关推荐
MOONICK1 小时前
数据结构——红黑树
数据结构
(●—●)橘子……1 小时前
记力扣2271.毯子覆盖的最多白色砖块数 练习理解
数据结构·笔记·python·学习·算法·leetcode
做运维的阿瑞1 小时前
Python 面向对象编程深度指南
开发语言·数据结构·后端·python
new coder2 小时前
[算法练习]第三天:定长滑动窗口
数据结构·算法
晨非辰3 小时前
《从数组到动态顺序表:数据结构与算法如何优化内存管理?》
c语言·数据结构·经验分享·笔记·其他·算法
new coder3 小时前
[算法练习]Day 4:定长滑动窗口
算法·leetcode
筱砚.3 小时前
【数据结构——十字链表】
网络·数据结构·链表
坚持编程的菜鸟5 小时前
LeetCode每日一题——重复的子字符串
数据结构·算法·leetcode
Swift社区7 小时前
LeetCode 390 消除游戏
算法·leetcode·游戏
williamdsy9 小时前
【MoonBit初探】:从一个“陷阱”到深入理解数据结构*
数据结构·map·moonbit