当前位置:网站首页>LeetCode每日一练 —— 876. 链表的中间结点
LeetCode每日一练 —— 876. 链表的中间结点
2022-07-27 18:33:00 【飞向星的客机】
前言
Wassup guys!我是Edison
今天是 LeetCode 上的 leetcode 876. 链表的中间结点
Let’s get it!

1. 题目分析
给定一个头结点为 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
示例 1:
示例 2:
2. 题目图解
这道题用的方法是 快慢指针法;
(1)定义慢指针 slow 一次走 1 步;
(2)定义快指针 fast 一次走 2 步;
奇数情况
当链表为 奇数 个时,首先,slow 和 fast 都指向第一个节点(如图所示)
然后 slow 一次走 1 步,fast 一次走 2 步,动图演示
当 fast 走到 尾节点 的时候,slow 指向的就是 中间节点
偶数情况
当链表为 偶数 个时,首先,slow 和 fast 都指向第一个节点(如图所示)
然后 slow 一次走 1 步,fast 一次走 2 步,动图演示
可以看到,当 fast 走到 NULL 时,slow 指向的就是 中间节点;
总结:
(1)当链表的节点数为 奇数 时,循环结束的条件就是 fast 走到 尾节点;
(2)当链表的节点数为 偶数 时,循环结束的条件就是 fast 走到 NULL;
3. 代码实现
接口代码
struct ListNode* middleNode(struct ListNode* head){
struct ListNode* slow, *fast;
slow = fast = head
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
提交结果
还要注意一点:在 while 循环判断部分,写的是继续的条件,想的是结束的条件!
边栏推荐
- 走马灯案例
- [Numpy] 数组索引和切片
- [deep learning] pytoch torch Autograd automatic differential engine
- Slim: self supervised point cloud scene flow and motion estimation (iccv 2021)
- Introduction to rk3399 platform introduction to proficient series (Introduction) 21 day learning challenge
- vant组件库
- [program life] "stage summary" - unwilling to be ordinary
- People call this software testing engineer. You're just making a living (with HR interview Dictionary)
- MySQL驱动jar包的下载--保姆教程
- [Numpy] 数组属性
猜你喜欢

Automatic test solution based on ATX

一种比读写锁更快的锁,还不赶紧认识一下

Go --- automatic recompilation of air

最新版web漏洞扫描工具AppScan\AWVS\Xray安装及使用教程

adb shell ls /system/bin(索引表)

AIRIOT答疑第6期|如何使用二次开发引擎?

Uncaught SyntaxError: redeclaration of let page

To do the test, you have to go to the big factory and disclose the "hidden rules" of bat big factory recruitment internally

SQL coding bug

Hexagon_V65_Programmers_Reference_Manual(6)
随机推荐
2022-07-19 advanced network engineering (XX) BGP route optimization, route optimization analysis one by one
Onion group joined hands with oceanbase to realize distributed upgrading, and global data has achieved cross cloud integration for the first time
Hexagon_V65_Programmers_Reference_Manual(7)
云管平台中租户以及多租户概念简单说明
Force deduction solution summary 592 fraction addition and subtraction
R语言dplyr包summarise_at函数计算dataframe数据中多个数据列(通过向量指定)的计数个数、均值和中位数、使用list函数指定函数列表(使用.符号和~符号指定函数语法purr)
MySQL basic queries and operators
金仓数据库 KingbaseES异构数据库移植指南 (3. KingbaseES移植能力支撑体系)
用户登录切换案例
82. (cesium article) cesium points move on 3D models
Slim: self supervised point cloud scene flow and motion estimation (iccv 2021)
R语言使用epiDisplay包的lroc函数可视化logistic回归模型的ROC曲线并输出诊断表(diagnostic table)、可视化多条ROC曲线、使用legend函数为可视化图像添加图例
R语言使用dplyr包左连接两个dataframe数据(left join)
北京/上海/广州/深圳DAMA-CDGA/CDGP数据治理认证报名条件
说透缓存一致性与内存屏障
金仓数据库 KingbaseES异构数据库移植指南 (2. 概述)
【防抖与节流】
自动化测试----selenium(二)
认识网络模型数据的封装和解封装
全局样式与图标