当前位置:网站首页>Leetcode simple question sharing (20)
Leetcode simple question sharing (20)
2022-07-07 13:39:00 【PigeonEssence】
876. The middle node of a list

This is a simple linked list problem , The core problem is to find the central point .
Because this linked list is not a two-way linked list , So we can't simply consider the idea of double pointer reverse traversal . So a fast and slow pointer is a good way .
The concept of fast and slow pointer is that the slow pointer takes one step at a time , Then he goes n The result of this time is n;
Two steps at a time , go n The result of this time is 2n.
Then when the fast pointer goes to the end of the linked list When , That is, the value of the fast pointer is null or the next one of the fast pointer is null . This is the node pointed by the slow pointer, which is the central node .
The code is as follows :
/**
* 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) {
// Slow pointer
ListNode slowPointer = head;
// Quick pointer
ListNode fastPointer = head;
// Jump out of the loop when the fast pointer is empty or the next node of the fast pointer is empty
while(fastPointer!=null && fastPointer.next!=null){
// Slow pointer one step
slowPointer = slowPointer.next;
// Let's go two steps
fastPointer = fastPointer.next.next;
}
// Return slow pointer
return slowPointer;
}
} 
边栏推荐
猜你喜欢

Esp32 ① compilation environment

118. 杨辉三角

My "troublesome" subordinates after 00: not bad for money, against leaders, and resist overtime

OSI 七层模型

室内ROS机器人导航调试记录(膨胀半径的选取经验)

Digital IC Design SPI

2022-7-7 Leetcode 844.比较含退格的字符串

QQ的药,腾讯的票

QQ medicine, Tencent ticket

10 pictures open the door of CPU cache consistency
随机推荐
How far can it go to adopt a cow by selling the concept to the market?
Scrapy教程经典实战【新概念英语】
【堡垒机】云堡垒机和普通堡垒机的区别是什么?
靠卖概念上市,认养一头牛能走多远?
[learning notes] zkw segment tree
Leecode3. Longest substring without repeated characters
Indoor ROS robot navigation commissioning record (experience in selecting expansion radius)
Detr introduction
[1] ROS2基础知识-操作命令总结版
交付效率提升52倍,运营效率提升10倍,看《金融云原生技术实践案例汇编》(附下载)
Simple and easy-to-use code specification
RealBasicVSR测试图片、视频
ESP32 ① 编译环境
postgresql array类型,每一项拼接
JS determines whether an object is empty
2022-7-6 Leetcode27.移除元素——太久没有做题了,为双指针如此狼狈的一天
【面试高频题】难度 2.5/5,简单结合 DFS 的 Trie 模板级运用题
MongoDB的用户管理总结
Write it down once Net a new energy system thread surge analysis
Mongodb replication (replica set) summary