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;
    }
};
相关推荐
papership2 小时前
【入门级-算法-6、排序算法:选择排序】
数据结构·算法·排序算法
共享家95272 小时前
优先搜索(DFS)实战
算法·leetcode·深度优先
flashlight_hi4 小时前
LeetCode 分类刷题:2563. 统计公平数对的数目
python·算法·leetcode
YS_Geo4 小时前
Redis 深度解析:数据结构、持久化与集群
数据结构·数据库·redis
楼田莉子4 小时前
C++算法专题学习:栈相关的算法
开发语言·c++·算法·leetcode
njxiejing4 小时前
Pandas数据结构(DataFrame,字典赋值)
数据结构·人工智能·pandas
tju新生代魔迷4 小时前
数据结构:单链表以及链表题
数据结构·链表
dragoooon344 小时前
[数据结构——lesson3.单链表]
数据结构·c++·leetcode·学习方法
hsjkdhs4 小时前
数据结构之链表(单向链表与双向链表)
数据结构·链表·指针
轮到我狗叫了5 小时前
力扣.1054距离相等的条形码力扣767.重构字符串力扣47.全排列II力扣980.不同路径III力扣509.斐波那契数列(记忆化搜索)
java·算法·leetcode