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;
    }
};
相关推荐
Alfred king21 分钟前
面试150 生命游戏
leetcode·游戏·面试·数组
水木兰亭41 分钟前
数据结构之——树及树的存储
数据结构·c++·学习·算法
Jess072 小时前
插入排序的简单介绍
数据结构·算法·排序算法
老一岁2 小时前
选择排序算法详解
数据结构·算法·排序算法
freexyn2 小时前
Matlab自学笔记六十一:快速上手解方程
数据结构·笔记·matlab
ysa0510302 小时前
Dijkstra 算法#图论
数据结构·算法·图论
醇醛酸醚酮酯4 小时前
基于多线程实现链表快排
数据结构·链表
小张成长计划..5 小时前
数据结构-栈的实现
开发语言·数据结构
薰衣草23337 小时前
一天两道力扣(1)
算法·leetcode·职场和发展
爱coding的橙子7 小时前
每日算法刷题Day41 6.28:leetcode前缀和2道题,用时1h20min(要加快)
算法·leetcode·职场和发展