当前位置:网站首页>数学解决——环形链表问题
数学解决——环形链表问题
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;
}
}边栏推荐
猜你喜欢

MPPT太阳能充放电控制器数据采集-通过网关采集电池电压容量电量SOC,wifi传输

Path and the largest

Shell 脚本循环遍历日志文件中的值进行求和并计算平均值,最大值和最小值

uniapp uses 3rd party fonts

静态路由解析(最长掩码匹配原则+主备路由)

最高月薪20K?平均薪资近万...在华为子公司工作是什么体验?

mmdetection trains a model related command

STM32CUBEMX开发GD32F303(11)----ADC在DMA模式下扫描多个通道

Software testing basic interface testing - getting started with Jmeter, you should pay attention to these things

Linux下redis7的安装,启动与停止
随机推荐
[1154] How to convert string to datetime
汉源高科8路HDMI综合多业务高清视频光端机8路HDMI视频+8路双向音频+8路485数据+8路E1+32路电话+4路千兆物理隔离网络
After reading "MySQL Database Advanced Practice" (SQL Xiao Xuzhu)
MySQL stored procedure
两个有序数组间相加和的Topk问题
[1154]如何将字符串转换为datetime
16. Registration Center-consul
Fiddler captures packets to simulate weak network environment testing
Simple confession page
如何在 go 程序中暴露 Prometheus 指标
The effective square of the test (one question of the day 7/29)
mysql view
Inner monologue from a female test engineer...
Arbitrum Interview | L2 Summer, what does the standout Arbitrum bring to developers?
Brute Force/Adjacency Matrix Breadth First Directed Weighted Graph Undirected Weighted Graph
To write good test cases, you must first learn test design
[Map and Set] LeetCode & Niu Ke exercise
Introduction to flask series 】 【 flask - using SQLAlchemy
Inter-vlan routing + static routing + NAT (PAT + static NAT) comprehensive experiment
Basic introduction to ShardingJDBC