当前位置:网站首页>LeetCode: 876. The middle node of the linked list —— simple
LeetCode: 876. The middle node of the linked list —— simple
2022-08-09 07:33:00 【Kinght_123】
题目
876. 链表的中间结点
给定一个头结点为 head 的非空单链表,返回链表的中间结点.
如果有两个中间结点,则返回第二个中间结点.
示例 1:
输入:[1,2,3,4,5]
输出:此列表中的结点 3 (序列化形式:[3,4,5])
返回的结点值为 3 . (测评系统对该结点序列化表述是 [3,4,5]).
注意,我们返回了一个 ListNode 类型的对象 ans,这样:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.
示例 2:
输入:[1,2,3,4,5,6]
输出:此列表中的结点 4 (序列化形式:[4,5,6])
由于该列表有两个中间结点,值分别为 3 和 4,我们返回第二个结点.
提示:
- 给定链表的结点数介于 1 和 100 之间.
解题思路
- 设定两个指针,一个指针走一步,一个指针走两步.
- When the two-step pointer reaches the end,The value pointed to by the other pointer is the answer.
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
cur1 = cur2 = head
while cur2 and cur2.next:
cur1 = cur1.next
cur2 = cur2.next.next
return cur1
运行结果
边栏推荐
- VOC格式标签转YOLO格式
- 查看日志常用命令
- unity第一课
- Snake game, C language
- 解决pycharm每次新建项目都要重新pip安装一些第三方库等问题
- rsync:recv_generator: mkdir (in backup) failed:Permission denied (13) |failed to set times on '.'
- P1505 [National Training Team] Tourism Tree Chain Breakdown
- Lottie系列三 :原理分析
- 74HC595芯片引脚说明
- 【Template】Tree Chain Segmentation P3384
猜你喜欢
Data storage implementation of SDRAM and read and write operations on its data
半导体新能源智能装备整机软件系统方案设计
C语言:打印菱形
Tkinter可以选择的颜色
Flexible and easy-to-use sql monitoring script part7
74HC595 chip pin description
差分约束-图论
Four departments including the Ministry of Industry and Information Technology promote green smart home products to the countryside
Learning Notes---Machine Learning
更改Jupyter Notebook默认打开目录
随机推荐
Lottie系列四:使用建议
虚拟机网卡报错:Bringing up interface eth0: Error: No suitable device found: no device found for connection
Native JDBC operation database
高项 04 项目变更管理
线程API
Use tensorflow.keras to build a neural network model modularly
failed (13: Permission denied) while connecting to upstream
EXCEL使用函数联调(find,mid,vlookup,xlookup)
Lottie系列一:介绍与使用
DSP+ARM+FPGA高速PCIE/千兆网口信号仿真介绍
Sklearn data preprocessing
Classes and Structures
yolov5检测数据集标签数量
【模板】树链剖分 P3384
【nuxt】服务器部署步骤
MUV LUV EXTRA 2019CCPC秦皇岛站J题 KMP
Important news丨.NET Core 3.1 will end support on December 13 this year
设备指纹详解之识别垃圾账号
浅识微服务架构
Change Jupyter Notebook default open directory