当前位置:网站首页>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 .
边栏推荐
- 网站服务器停止响应是什么意思?
- Part 67: conversion between keypoint and point2f in opencv
- 模块二作业
- Seventy second: pedestrian detection
- ShardingSphere数据分片
- 什么叫做 inode ?带你理解 inode 和对于创建文件和删除文件时 inode 都提供了哪些帮助。
- Programming password guessing game
- Piziheng embedded: the method of making source code into lib Library under MCU Xpress IDE and its difference with IAR and MDK
- 牛市还没有结束,还有下半场 2021-05-18
- Stm32- analyze latency based on assembly
猜你喜欢
随机推荐
BOM browser object model
Kubernetes网络插件详解 - Calico篇 - 概述
The GUI interface of yolov3 (3) -- solve the out of memory problem and add camera detection function
Yolov3 trains its own data set
J9数字论:什么是DAO模式?DAO发展过程的阻碍
【一库】mapbox-gl!一款开箱即用的地图引擎
通货膨胀之下,后市如何操作?2021-05-14
Unity—欧拉角,四元数
VSCode格式化Json文件
The mobile version of Duoyu security browser will add new functions to make users browse more personalized
Practical experience of pair programming
Weight file and pre training file of yolov3
二叉树——104. 二叉树的最大深度
栈与队列——347. 前 K 个高频元素
牛市还没有结束,还有下半场 2021-05-18
二叉树相关知识
SHIB(柴犬币)一月涨幅数百倍,百倍币需具备哪些核心要素?2021-05-09
二叉树——222. 完全二叉树的节点个数
How to use yolov5 as an intelligent transportation system for red light running monitoring (1)
Key and difficult points of C language pointer









