当前位置:网站首页>Find the intermediate node of the linked list
Find the intermediate node of the linked list
2022-07-26 00:05:00 【Tell a joke hahaha】
Fast and slow pointer method , Define a fast And a slow. Give Way fast The speed of slow Twice the speed , When fast To the last node of the linked list ,slow At the middle node , This is the time , Output slow.
Two ways of writing :
The first one is :
public ListNode middleNode(){
// When fast The speed of slow At twice the speed , When fast When you get to the last node ,slow In the middle .
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
The second kind :
public ListNode middleNode(){
// When fast The speed of slow At twice the speed , When fast When you get to the last node ,slow In the middle .
ListNode fast = head;
ListNode slow = head;
while(fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
The difference between the first and the second :
- When the length of the linked list is odd , The results of the two calculations are the same
- When the linked list is even , There are two intermediate nodes , The intermediate nodes of the first calculation are two On the right the , The second way is On the left the .
边栏推荐
猜你喜欢

Shardingsphere data slicing

Fixed and alternate sequential execution of modes

VSCode格式化Json文件

牛市还将继续,拿好手里的币 2021-05-08

抽丝剥茧C语言(高阶)程序环境和预处理
![[learning notes] unreal 4 engine introduction (III)](/img/c2/2e6023c72652c77577f8f21684d07e.png)
[learning notes] unreal 4 engine introduction (III)
![[learning notes] solid works operation record](/img/f7/0535b473755643ce32996f00fa5554.png)
[learning notes] solid works operation record

Program environment and pretreatment

Dead letter queue and message TTL expiration code

行为型模式之迭代器模式
随机推荐
String functions and memory operation functions
本轮牛市还能持续多久?|疑问解答 2021-05-11
Article 75: writing skills of academic papers
Key and difficult points of C language pointer
Prometheus 运维工具 Promtool (二) Query 功能
Chapter 64: error lnk2019: unresolved external symbol cvround
“群魔乱舞”,牛市是不是结束了?2021-05-13
Firewall command simple operation
网站服务器停止响应是什么意思?
Basic syntax of MySQL DDL, DML and DQL
什么是奇偶校验?如何用C语言实现?
LeetCode_55_跳跃游戏
Binary tree -- 104. Maximum depth of binary tree
Leetcode107-二叉树的层序遍历II详解
A brief introduction to OWASP
Solve the problem of rapid index bar extrusion
二叉树——226. 翻转二叉树
SQLZOO——Nobel Quiz
如何用yolov5 做个闯红灯监控的智能交通系统(1)
STM32 pit encountered when using timer to do delay function