当前位置:网站首页>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;
};
边栏推荐
猜你喜欢
随机推荐
SmobilerService 推送实现
Classical Architecture and Memory Classification of Embedded Software Components
微信多开批处理(自动获取安装路径)
巴比特 | 元宇宙每日必读:玩家离场,平台关停,数字藏品市场正逐渐降温,行业的未来究竟在哪里?...
CDH6.3.2开启kerberos认证
3分钟实现内网穿透(基于ngrok实现)
Lease recovery system based on PHP7.2+MySQL5.7
XDR平台架构与关键技术解析
C#/VB.NET 从PDF中提取表格
一个扛住 100 亿次请求的红包系统,写得太好了!!
CADEditorX ActiveX 14.1.X
【MySQL功法】第2话 · 数据库与数据表的基本操作
矩阵的计算[通俗易懂]
多态详细讲解(简单实现买票系统模拟,覆盖/重定义,多态原理,虚表)
「全球数字经济大会」登陆 N 世界,融云提供通信云服务支持
What is the ERC20 token standard?
Machine Learning (Chapter 1) - Feature Engineering
Machines need tokens more than people
ABAB-740新语法
完全背包问题

![[Bubble sort and odd-even sorting]](/img/89/d63afe1900a05b2a5615fcc3c09ccb.png)






