当前位置:网站首页>数学解决——环形链表问题
数学解决——环形链表问题
2022-07-31 02:13:00 【陈亦康】
环形链表
思路:
- 先通过快慢双指针去遍历链表,直到fast与slow相遇停止(fast的速度必须是slow速度的二倍,不能是三倍、四倍...试想如果环只有两个结点,fast肯定先进环,若后进环slow刚好与fast错开,slow走三倍,fast走两步,是永远不会相遇的!)
- 再让一个指针从头节点遍历,另一个指针从上一次快慢指针相遇处遍历,两个指针的遍历速度一致必定会在循环的结点入口相遇,想不来?解释如下图:
代码如下:
public class Solution {
public ListNode detectCycle(ListNode head) {
//快指针必须是慢指针速度的二倍
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
break;
}
}
if(fast == null || fast.next == null){
return null;
}
slow = head;
while(slow != fast){
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
边栏推荐
猜你喜欢
uniapp uses 3rd party fonts
Introduction to flask series 】 【 flask - using SQLAlchemy
leetcode-952: Calculate max component size by common factor
基于FPGA的售货机
leetcode-399: division evaluation
软件测试报告有哪些内容?
Arbitrum Interview | L2 Summer, what does the standout Arbitrum bring to developers?
mmdetection训练一个模型相关命令
vlan间路由+静态路由+NAT(PAT+静态NAT)综合实验
汉源高科8路HDMI综合多业务高清视频光端机8路HDMI视频+8路双向音频+8路485数据+8路E1+32路电话+4路千兆物理隔离网络
随机推荐
Charging effect simulation
f.grid_sample
leetcode-1161: Maximum in-layer element sum
User interaction + formatted output
The PC side determines the type of browser currently in use
静态路由+PAT+静态NAT(讲解+实验)
Mathematical Ideas in AI
MySQL installation tutorial (detailed, package teaching package~)
coldfusion8 background scheduled tasks take shell
vlan间路由+静态路由+NAT(PAT+静态NAT)综合实验
Linux下redis7的安装,启动与停止
力扣刷题之有效的正方形(每日一题7/29)
Observer mode (1)
Is there a way to earn 300 yuan a day by doing a side business?
cudaMemcpy study notes
BAT卖不动「医疗云」:医院逃离、山头林立、行有行规
Nacos
Coldfusion file read holes (CVE - 2010-2861)
leetcode-128: longest continuous sequence
Brute Force/Adjacency Matrix Breadth First Directed Weighted Graph Undirected Weighted Graph