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

Are you still working hard on the limit of MySQL paging?

软件测试报告有哪些内容?
![[Map and Set] LeetCode & Niu Ke exercise](/img/66/d812a6ad854cb0993c796760042150.png)
[Map and Set] LeetCode & Niu Ke exercise

ShardingJDBC基本介绍

Fiddler captures packets to simulate weak network environment testing

Unity界面总体介绍

12 pictures take you to fully understand service current limit, circuit breaker, downgrade, and avalanche

934. The Shortest Bridge

【Bank Series Phase 1】People's Bank of China
![[WeChat applet] This article takes you to understand data binding, event binding, event parameter transfer, and data synchronization](/img/f8/8437783794c2007a74c0a153d85102.png)
[WeChat applet] This article takes you to understand data binding, event binding, event parameter transfer, and data synchronization
随机推荐
STM32CUBEMX develops GD32F303 (11) ---- ADC scans multiple channels in DMA mode
Calculate S=a+aa+…+aa…a
coldfusion8 background scheduled tasks take shell
Drools基本介绍,入门案例,基本语法
Teach you how to configure Jenkins automated email notifications
multiplayer-hlap 包有问题,无法升级的解决方案
【AcWing 62nd Weekly Game】
Face detection based on opencv
MySQL installation tutorial (detailed, package teaching package~)
Crypto Life, a day in the life of a Web3 project partner
软件测试缺陷报告---定义,组成,缺陷的生命周期,缺陷跟踪产后处理流程,缺陷跟踪处理流程,缺陷跟踪的目的,缺陷管理工具
两个有序数组间相加和的Topk问题
加密生活,Web3 项目合伙人的一天
Nacos
Unity界面总体介绍
验证整数输入
完整复制虚拟机原理(云计算)
AtCoder Beginner Contest 261 部分题解
First acquaintance with C language -- array
16. Registration Center-consul