当前位置:网站首页>LeetCode:876. 链表的中间结点————简单
LeetCode:876. 链表的中间结点————简单
2022-08-09 07:28: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 之间。
解题思路
- 设定两个指针,一个指针走一步,一个指针走两步。
- 当走两步的指针到达终点时,另一个指针所指向的数值就是答案。
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
运行结果
边栏推荐
猜你喜欢
随机推荐
Invoker 2019CCPC秦皇岛站I题 简单DP
MVN 中配置flyway mysq
The maximum validity period of an SSL certificate is 13 months. Is it necessary to apply for multiple years at a time?
高项 03 项目立项管理
SiamFC:用于目标跟踪的全卷积孪生网络 fully-convolutional siamese networks for object tracking
类和结构体
解决pycharm每次新建项目都要重新pip安装一些第三方库等问题
分布式事务的应用场景
错误:为 repo ‘oracle_linux_repo‘ 下载元数据失败 : Cannot download repomd.xml: Cannot download repodata/repomd.
排序第二节——选择排序(选择排序+堆排序)(两个视频讲解)
pytorch指定GPU
failed (13: Permission denied) while connecting to upstream
【模板】树链剖分 P3384
【nuxt】服务器部署步骤
Colors that Tkinter can choose from
【Template】Tree Chain Segmentation P3384
way of thinking problem-solving skills
HDU - 3183 A Magic Lamp Segment Tree
SAP ALV 数据导出被截断的bug
2017icpc沈阳 G Infinite Fraction Path BFS+剪枝