当前位置:网站首页>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;
};
边栏推荐
- Skills required to be a good architect: How to draw a system architecture that everyone will love?What's the secret?Come and open this article to see it!...
- 小身材有大作用——光模块寿命分析(二)
- Simple implementation of a high-performance clone of Redis using .NET (1)
- [错题]电路维修
- C - 为什么指针常常初始化为 NULL?
- How to use outside the PHP command in the container
- Traceback (most recent call last): File
- ERC20通证标准是什么?
- 3分钟实现内网穿透(基于ngrok实现)
- 【HCIP持续更新】STP协议相关保护机制
猜你喜欢

零拷贝、MMAP、堆外内存,傻傻搞不明白...

微信小程序获取用户手机号码

【MySQL功法】第4话 · 和kiko一起探索MySQL中的运算符
![LeetCode 899 有序队列[字典序] HERODING的LeetCode之路](/img/95/1b63cfb25b9e0802666114f089fcb8.png)
LeetCode 899 有序队列[字典序] HERODING的LeetCode之路

MySQL - 2059 - Authentication plugin ‘caching_sha2_password‘ cannot be loaded

How to use outside the PHP command in the container

FR9811S6 SOT-23-6 23V, 2A Synchronous Step-Down DC/DC Converter

完全背包问题的思路解析

html+css+php+mysql实现注册+登录+修改密码(附完整代码)

成为优秀架构师必备技能:怎样才能画出让所有人赞不绝口的系统架构图?秘诀是什么?快来打开这篇文章看看吧!...
随机推荐
【文件IO的简单实现】
试题G:单词分析 ← 第十一届蓝桥杯大赛第二场省赛赛题
Traceback (most recent call last): File
笔试题:金额拆分
viewstub 的详细用法_pageinfo用法
代码分析Objective-C中的深拷贝与浅拷贝
[Wrong title] Circuit maintenance
This article takes you to understand the principle of CDN technology
[Bubble sort and odd-even sorting]
LeetCode——1161. 最大层内元素和
本周四晚19:00知识赋能第4期直播丨OpenHarmony智能家居项目之设备控制实现
二叉搜索树(搜索二叉树)模拟实现(有递归版本)
请问应该用什么关键字将内容主题设置为 dark 呢
干货!一种被称为Deformable Butterfly(DeBut)的高度结构化且稀疏的线性变换
Realize 2d characters move left and right while jumping
html网页如何获取后台数据库的数据(html + ajax + php + mysql)
Analysis of the idea of the complete knapsack problem
JS快速高效开发技巧指南(持续更新)
What is a smart contract?
Skills required to be a good architect: How to draw a system architecture that everyone will love?What's the secret?Come and open this article to see it!...