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;
    }
};
相关推荐
Pniubi43 分钟前
力扣543二叉树的直径(深度优先搜索法(递归))
算法·leetcode·职场和发展
黎相思1 小时前
BTree
数据结构·b树·b+树
UIU11412 小时前
P1233 [ICPC 2001 Taejon R] 木棍加工
数据结构·c++·算法·动态规划
niyongsheng14 小时前
3D 装箱算法工程化:数据结构、放置启发式与支撑规则
数据结构·算法·rust
叉烧滑蛋17 小时前
B站台湾大学郭彦甫|MATLAB 学习笔记|04 变量与档案存取
数据结构
j7~17 小时前
【穷举、深搜与回溯算法】一棵决策树讲透全排列与子集
数据结构·c++·算法·leetcode·回溯·递归
Shaoshing19 小时前
LeetCode100 42.接雨水
java·算法·leetcode
文丑颜不良啊20 小时前
LeetCode1261~1280题目解析
java·leetcode
not coder20 小时前
一文讲通--从树到红黑树
数据结构·算法
爱吃香菜的初学者20 小时前
八.数据结构——哈希表(1)
数据结构·散列表