当前位置:网站首页>数学解决——环形链表问题
数学解决——环形链表问题
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;
}
}边栏推荐
猜你喜欢
随机推荐
f.grid_sample
Calculate S=a+aa+…+aa…a
[1154] How to convert string to datetime
What level of software testing does it take to get a 9K job?
PDF 拆分/合并
What does a software test report contain?
Software Testing Defect Reporting - Definition, Composition, Defect Lifecycle, Defect Tracking Post-Production Process, Defect Tracking Process, Purpose of Defect Tracking, Defect Management Tools
mysql view
【银行系列第一期】中国人民银行
Static routing + PAT + static NAT (explanation + experiment)
修改未正确放入沙盒造成苹果兼容性问题
16. Registration Center-consul
基于FPGA的图像实时采集
Inner monologue from a female test engineer...
What is the ideal college life?
直播预告 | KDD2022博士论文奖冠亚军对话
mmdetection trains a model related command
MySQL stored procedure
Interprocess communication study notes
Force buckled brush the stairs (7/30)







![CV-Model [3]: MobileNet v2](/img/c7/1155a1f610110724c67a3b7557ef28.jpg)

