当前位置:网站首页>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;
}
} 
边栏推荐
猜你喜欢

Thread pool reject policy best practices

实现IP地址归属地显示功能、号码归属地查询

Cinnamon 任务栏网速
![[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
![Scripy tutorial classic practice [New Concept English]](/img/bc/f1ef8b6de6bfb6afcdfb0d45541c72.png)
Scripy tutorial classic practice [New Concept English]

Scrapy教程经典实战【新概念英语】

How to make join run faster?

OSI seven layer model

1. Deep copy 2. Call apply bind 3. For of in differences

Vscade editor esp32 header file wavy line does not jump completely solved
随机推荐
Detr introduction
【面试高频题】难度 2.5/5,简单结合 DFS 的 Trie 模板级运用题
My "troublesome" subordinates after 00: not bad for money, against leaders, and resist overtime
Read PG in data warehouse in one article_ stat
High end for 8 years, how is Yadi now?
MongoDB优化的几点原则
JS slow motion animation principle teaching (super detail)
[etc.] what are the security objectives and implementation methods that cloud computing security expansion requires to focus on?
Realize the IP address home display function and number home query
[learning notes] segment tree selection
Shell batch file name (excluding extension) lowercase to uppercase
Unity build error: the name "editorutility" does not exist in the current context
Cinnamon taskbar speed
服务器到服务器 (S2S) 事件 (Adjust)
Summary of import, export, backup and recovery of mongodb
LIS longest ascending subsequence problem (dynamic programming, greed + dichotomy)
About how appium closes apps (resolved)
Getting started with cinnamon applet
聊聊伪共享
MATLAB中polarscatter函数使用