当前位置:网站首页>数学解决——环形链表问题
数学解决——环形链表问题
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;
}
}边栏推荐
- leetcode-128: longest continuous sequence
- 加密生活,Web3 项目合伙人的一天
- 【AcWing 62nd Weekly Game】
- Intranet Infiltration - Privilege Escalation
- Crawler text data cleaning
- 项目开发软件目录结构规范
- 二层广播风暴(产生原因+判断+解决)
- leetcode-399: division evaluation
- Unity界面总体介绍
- My first understanding of MySql, and the basic syntax of DDL and DML and DQL in sql statements
猜你喜欢
![[Map and Set] LeetCode & Niu Ke exercise](/img/66/d812a6ad854cb0993c796760042150.png)
[Map and Set] LeetCode & Niu Ke exercise

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

uniapp uses 3rd party fonts

There is a problem with the multiplayer-hlap package and the solution cannot be upgraded

mmdetection trains a model related command

STP选举(步骤+案列)详解

MySql installation and configuration super detailed tutorial and simple method of building database and table

Introduction and use of Drools WorkBench

一个无经验的大学毕业生,可以转行做软件测试吗?我的真实案例
![The comprehensive result of the case statement, do you know it?[Verilog Advanced Tutorial]](/img/8a/28427aa773e46740eda9e95f6669f2.png)
The comprehensive result of the case statement, do you know it?[Verilog Advanced Tutorial]
随机推荐
一个无经验的大学毕业生,可以转行做软件测试吗?我的真实案例
力扣刷题之爬楼梯(7/30)
16. Registration Center-consul
Drools基本介绍,入门案例,基本语法
验证整数输入
VSCode Plugin: Nested Comments
General introduction to the Unity interface
类似 MS Project 的项目管理工具有哪些
C语言小程序 -- 常见经典练习题
来自一位女测试工程师的内心独白...
汉源高科8路HDMI综合多业务高清视频光端机8路HDMI视频+8路双向音频+8路485数据+8路E1+32路电话+4路千兆物理隔离网络
最高月薪20K?平均薪资近万...在华为子公司工作是什么体验?
934. The Shortest Bridge
Can an inexperienced college graduate switch to software testing?my real case
mysql 视图
Problems that need to be solved by the tcp framework
[1154] How to convert string to datetime
【Bank Series Phase 1】People's Bank of China
Validate XML documents
Brute Force/Adjacency Matrix Breadth First Directed Weighted Graph Undirected Weighted Graph