当前位置:网站首页>Mathematics to solve the problem - circular linked list
Mathematics to solve the problem - circular linked list
2022-07-31 02:20:00 【Chen Yikang】
Circular linked list
Things:
- First traverse the linked list through the fast and slow double pointers until the fast and slow meet and stop (The speed of fast must be twice the speed of slow, not three or four times... Imagine if the ring has only two knotsPoint, the fast must be advanced in the ring, if the slow in the backward ring is just staggered from the fast, the slow takes three times, and the fast takes two steps, and they will never meet!)
- Let one pointer be traversed from the head node, and the other pointer will be traversed from the point where the speed and slow pointers met last time, The traversal speed of the two pointers is the same and they will meet at the node entrance of the loop, I can't think of it?The explanation is as follows:
The code is as follows:
public class Solution {public ListNode detectCycle(ListNode head) {//fast pointer must be twice as fast as slow pointerListNode 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;}}
边栏推荐
猜你喜欢
mmdetection trains a model related command
英特尔软硬优化,赋能东软加速智慧医疗时代到来
After reading "MySQL Database Advanced Practice" (SQL Xiao Xuzhu)
LeetCode 1161 最大层内元素和[BFS 二叉树] HERODING的LeetCode之路
User interaction + formatted output
Detailed explanation of STP election (step + case)
What have I experienced to become a tester who is harder than development?
经典链表OJ强训题——快慢双指针高效解法
"Cloud native's master, master and vulgar skills" - 2022 National New College Entrance Examination Volume I Composition
General introduction to the Unity interface
随机推荐
Simple confession page
数学解决——环形链表问题
What are the project management tools like MS Project
BAT can't sell "Medical Cloud": Hospitals flee, mountains stand, and there are rules
Crawler text data cleaning
Shell 脚本循环遍历日志文件中的值进行求和并计算平均值,最大值和最小值
First acquaintance with C language -- array
【AcWing 62nd Weekly Game】
AI在医疗影像设备全流程应用
两个有序数组间相加和的Topk问题
如何在 go 程序中暴露 Prometheus 指标
Between two orderly array of additive and Topk problem
PDF split/merge
Path and the largest
Is there a way to earn 300 yuan a day by doing a side business?
keep-alive cache component
The PC side determines the type of browser currently in use
CMOS和TTL的区别?
二层广播风暴(产生原因+判断+解决)
Calculate S=a+aa+…+aa…a