当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢
DID登陆-MetaMask
Distributed transaction solution
My "troublesome" subordinates after 00: not bad for money, against leaders, and resist overtime
室內ROS機器人導航調試記錄(膨脹半徑的選取經驗)
数字ic设计——SPI
如何让join跑得更快?
Enregistrement de la navigation et de la mise en service du robot ROS intérieur (expérience de sélection du rayon de dilatation)
LIS 最长上升子序列问题(动态规划、贪心+二分)
Talk about pseudo sharing
1、深拷贝 2、call apply bind 3、for of for in 区别
随机推荐
[etc.] what are the security objectives and implementation methods that cloud computing security expansion requires to focus on?
实现IP地址归属地显示功能、号码归属地查询
Cinnamon Applet 入门
MySQL error 28 and solution
《厌女:日本的女性嫌恶》摘录
PAcP learning note 3: pcap method description
Ogre入门尝鲜
PHP - laravel cache
简单好用的代码规范
PACP学习笔记一:使用 PCAP 编程
error LNK2019: 无法解析的外部符号
Why can basic data types call methods in JS
xshell连接服务器把密钥登陆改为密码登陆
Navicat运行sql文件导入数据不全或导入失败
Summary of import, export, backup and recovery of mongodb
MongoDB的导入导出、备份恢复总结
提升树莓派性能的方法
ESP32 ① 编译环境
High end for 8 years, how is Yadi now?
单片机原理期末复习笔记