当前位置:网站首页>142、环形链表||
142、环形链表||
2022-04-23 10:11:00 【Popuessing's Jersey】
题意: 给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
进阶挑战:不允许修改给定的链表。
方法:快慢指针(双指针)
public class Huanxinglianbiao2 {
public ListNode detectCycle(ListNode head){
//设置快慢指针
ListNode fast = head;
ListNode slow = head;
while(fast!=null && fast.next!=null){
//快指针走两步
//慢指针走一步
fast = fast.next.next;
slow = slow.next;
//如果fast == slow确认有环
//找到快慢指针的相遇点,再相遇点快指针回到head,慢指针保持不动
//他们再以相同的速度前进,当他们再次相遇的点,就是环形入口的入口点了
if (fast == slow){
fast = head;
while (fast!=slow){
fast = fast.next;
slow = slow.next;
}
//返回环的入口
return fast;
}
}
//遍历链表结束,没有找到环,则返回空;
return null;
}
}
版权声明
本文为[Popuessing's Jersey]所创,转载请带上原文链接,感谢
https://blog.csdn.net/CoCo629vanilla/article/details/121442007
边栏推荐
- 中控学习型红外遥控模块支持网络和串口控制
- 使用IDEA开发Spark程序
- 最长公共前串
- The central control learning infrared remote control module supports network and serial port control
- Chapter 2 Oracle database in memory architecture (I) (im-2.1)
- 2022年流动式起重机司机考试题库模拟考试平台操作
- 正大国际讲解道琼斯工业指数到底是什么?
- Go language practice mode - functional options pattern
- DBA常用SQL语句 (5) - Latch 相关
- 自定义登录失败处理
猜你喜欢
JUC concurrent programming 07 -- is fair lock really fair (source code analysis)
0704、ansible----01
计算机网络安全实验二|DNS协议漏洞利用实验
Yarn资源调度器
Epidemic prevention registration applet
"Gu Yu series" airdrop
构建元宇宙时代敏捷制造的九种能力
Question bank and answers of Shanghai safety officer C certificate examination in 2022
NEC infrared remote control coding description
Sim Api User Guide(5)
随机推荐
shell脚本免交互
Exercise questions and simulation test of refrigeration and air conditioning equipment operation test in 2022
[2020wc Day2] F. Clarice picking mushrooms (subtree and query, light and heavy son thought)
0704、ansible----01
構建元宇宙時代敏捷制造的九種能力
计算机网络安全实验二|DNS协议漏洞利用实验
Sim Api User Guide(8)
杰理之栈溢出 stackoverflow 怎么办?【篇】
2022 mobile crane driver test question bank simulation test platform operation
第一章 Oracle Database In-Memory 相关概念(IM-1.1)
LeetCode 1249. Minimum Remove to Make Valid Parentheses - FB高频题1
通过流式数据集成实现数据价值(5)- 流分析
Sim Api User Guide(4)
Depth selector
DBA常用SQL语句(3)- cache、undo、索引和等待事件
Yarn资源调度器
2022年流动式起重机司机考试题库模拟考试平台操作
[COCI] Vje š TICA (subset DP)
自定义登录失败处理
第二章 Oracle Database In-Memory 体系结构(上) (IM-2.1)