当前位置:网站首页>LeetCode-142. 环形链表 II
LeetCode-142. 环形链表 II
2022-08-03 11:29:00 【边界流浪者】
给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
不允许修改 链表。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:返回索引为 1 的链表节点
解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:
输入:head = [1,2], pos = 0
输出:返回索引为 0 的链表节点
解释:链表中有一个环,其尾部连接到第一个节点。
示例 3:
输入:head = [1], pos = -1
输出:返回 null
解释:链表中没有环。
提示:
链表中节点的数目范围在范围 [0, 104] 内
-105 <= Node.val <= 105
pos 的值为 -1 或者链表中的一个有效索引
进阶:你是否可以使用 O(1) 空间解决此题?
#include <iostream>
#include <unordered_map>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
int index = 0;
ListNode *t = head;
if(t == nullptr){
return t;
}
hash[t] = index;
while(t->next!=nullptr){
t = t->next;
if(hash.count(t)!=0){
return t;
}else{
hash[t] = ++index;
}
}
return nullptr;
}
private:
unordered_map<ListNode *, int> hash;
};
边栏推荐
猜你喜欢

干货!一种被称为Deformable Butterfly(DeBut)的高度结构化且稀疏的线性变换

LyScript implements memory stack scanning

Summary of redis basics - data types (strings, lists, sets, hashes, sets)

ABAB-740新语法
![[Detailed explanation of binary search plus recursive writing method] with all the code](/img/51/c4960575a59f8ca7f161b310e47b27.png)
[Detailed explanation of binary search plus recursive writing method] with all the code
![[Star Project] Little Hat Plane Battle (9)](/img/e3/c7d2728080bcdccc181a7e5c50ee6f.png)
[Star Project] Little Hat Plane Battle (9)
![[Bubble sort and odd-even sorting]](/img/89/d63afe1900a05b2a5615fcc3c09ccb.png)
[Bubble sort and odd-even sorting]

Machine Learning (Chapter 1) - Feature Engineering

XDR平台架构与关键技术解析

【二分查找详解外加递归写法】附有全部代码
随机推荐
【MySQL】数据库进阶之索引内容详解(上篇 索引分类与操作)
ERC20通证标准是什么?
小身材有大作用——光模块基础知识(一)
complete knapsack problem
asdn涨薪技术之apifox+Jenkins如何玩转接口自动化测试
This article takes you to understand the principle of CDN technology
云原生 Dev0ps 实践
Lease recovery system based on PHP7.2+MySQL5.7
XDR平台架构与关键技术解析
进程内存
LyScript 实现对内存堆栈扫描
微信为什么使用 SQLite 保存聊天记录?
[错题]电路维修
【二分查找详解外加递归写法】附有全部代码
[Bubble sort and odd-even sorting]
完全背包问题
[论文阅读] (23)恶意代码作者溯源(去匿名化)经典论文阅读:二进制和源代码对比
MySQL database combat (1)
【多线程的相关内容】
MySQL数据库实战(1)