当前位置:网站首页>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;
}
} 
边栏推荐
- Mongodb meets spark (for integration)
- MongoDB优化的几点原则
- Show the mathematical formula in El table
- Why can basic data types call methods in JS
- shell 批量文件名(不含扩展名)小写改大写
- 【黑马早报】华为辟谣“军师”陈春花;恒驰5预售价17.9万元;周杰伦新专辑MV 3小时播放量破亿;法华寺回应万元月薪招人...
- 云计算安全扩展要求关注的安全目标和实现方式区分原则有哪些?
- 1. Deep copy 2. Call apply bind 3. For of in differences
- ESP32构解工程添加组件
- [QNX Hypervisor 2.2用户手册]6.3.4 虚拟寄存器(guest_shm.h)
猜你喜欢

Vscade editor esp32 header file wavy line does not jump completely solved

线程池拒绝策略最佳实践

如何让join跑得更快?

分布式事务解决方案

Digital IC Design SPI

我那“不好惹”的00后下属:不差钱,怼领导,抵制加班

JS缓动动画原理教学(超细节)

干货|总结那些漏洞工具的联动使用

Cmake learning and use notes (1)
![[dark horse morning post] Huawei refutes rumors about](/img/d7/4671b5a74317a8f87ffd36be2b34e1.jpg)
[dark horse morning post] Huawei refutes rumors about "military master" Chen Chunhua; Hengchi 5 has a pre-sale price of 179000 yuan; Jay Chou's new album MV has played more than 100 million in 3 hours
随机推荐
Realbasicvsr test pictures and videos
Error lnk2019: unresolved external symbol
【面试高频题】难度 2.5/5,简单结合 DFS 的 Trie 模板级运用题
LIS 最长上升子序列问题(动态规划、贪心+二分)
Digital IC Design SPI
信号强度(RSSI)知识整理
交付效率提升52倍,运营效率提升10倍,看《金融云原生技术实践案例汇编》(附下载)
Clion mingw64 Chinese garbled code
Enregistrement de la navigation et de la mise en service du robot ROS intérieur (expérience de sélection du rayon de dilatation)
centso7 openssl 报错Verify return code: 20 (unable to get local issuer certificate)
cmake 学习使用笔记(一)
MongoDB内部的存储原理
室内ROS机器人导航调试记录(膨胀半径的选取经验)
MongoDB 分片总结
Drawerlayout suppress sideslip display
一文读懂数仓中的pg_stat
Mongodb slice summary
MySQL error 28 and solution
JNA学习笔记一:概念
Introduce six open source protocols in detail (instructions for programmers)