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;
    }
};
相关推荐
似水এ᭄往昔1 天前
【C++】--AVL树的认识和实现
开发语言·数据结构·c++·算法·stl
TL滕1 天前
从0开始学算法——第十六天(双指针算法)
数据结构·笔记·学习·算法
天赐学c语言1 天前
12.14 - 搜索旋转排序数组 && 判断两个结构体是否相等
数据结构·c++·算法·leecode
1024肥宅1 天前
JavaScript 性能与优化:数据结构和算法
前端·数据结构·算法
仰泳的熊猫1 天前
1112 Stucked Keyboard
数据结构·c++·算法·pat考试
he___H1 天前
滑动窗口一题
java·数据结构·算法·滑动窗口
AI科技星1 天前
统一场论质量定义方程:数学验证与应用分析
开发语言·数据结构·经验分享·线性代数·算法
学编程就要猛1 天前
数据结构初阶:Map和Set接口
数据结构
jianfeng_zhu1 天前
不带头节点的链式存储实现链栈
数据结构·算法
lightqjx1 天前
【算法】双指针
c++·算法·leetcode·双指针