当前位置:网站首页>LeetCode简单题分享(20)
LeetCode简单题分享(20)
2022-07-07 11:36:00 【PigeonEssence】

这是一个简单的链表问题,其中的核心问题就是找到中心点。
因为这个链表并不是一个双向链表,所以不能简单的考虑双指针反向遍历的想法。所以快慢指针是一个好的办法。
快慢指针的概念就是慢指针每次走一步,那么他走n次的结果就是n;
快指针每次走两步,走n次的结果就是2n。
那么当快指针走到链表末尾的 时候,也就是快指针的值为空或者快指针的下一个是空。这是慢指针指向的节点就是中心节点。
代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode middleNode(ListNode head) {
//慢指针
ListNode slowPointer = head;
//快指针
ListNode fastPointer = head;
//快指针为空或者快指针的下一个节点为空的时候跳出循环
while(fastPointer!=null && fastPointer.next!=null){
//慢指针走一步
slowPointer = slowPointer.next;
//快指针走两步
fastPointer = fastPointer.next.next;
}
//返回慢指针
return slowPointer;
}
} 
边栏推荐
- php——laravel缓存cache
- move base参数解析及经验总结
- 我那“不好惹”的00后下属:不差钱,怼领导,抵制加班
- [learning notes] agc010
- How to make join run faster?
- [learning notes] segment tree selection
- Pay close attention to the work of safety production and make every effort to ensure the safety of people's lives and property
- 简单好用的代码规范
- ESP32 ① 编译环境
- Split screen bug notes
猜你喜欢
随机推荐
Japanese government and enterprise employees got drunk and lost 460000 information USB flash drives. They publicly apologized and disclosed password rules
我那“不好惹”的00后下属:不差钱,怼领导,抵制加班
Pay close attention to the work of safety production and make every effort to ensure the safety of people's lives and property
LeetCode_ Binary search_ Medium_ 153. Find the minimum value in the rotation sort array
xshell连接服务器把密钥登陆改为密码登陆
Vscode编辑器ESP32头文件波浪线不跳转彻底解决
About how appium closes apps (resolved)
648. 单词替换 : 字典树的经典运用
MongoDB的导入导出、备份恢复总结
Drawerlayout suppress sideslip display
clion mingw64中文乱码
Mongodb command summary
工具箱之 IKVM.NET 项目新进展
MySQL error 28 and solution
[learning notes] segment tree selection
交付效率提升52倍,运营效率提升10倍,看《金融云原生技术实践案例汇编》(附下载)
Solve the cache breakdown problem
DID登陆-MetaMask
JS中为什么基础数据类型可以调用方法
Error lnk2019: unresolved external symbol




![Scripy tutorial classic practice [New Concept English]](/img/bc/f1ef8b6de6bfb6afcdfb0d45541c72.png)




