当前位置:网站首页>力扣5_876. 链表的中间结点
力扣5_876. 链表的中间结点
2022-07-08 00:39:00 【上课不要睡觉了】
给定一个头结点为 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 之间。
来源:力扣(LeetCode)
Java解法1
这里使用了类似C语言里面的双指针的方法,快指针每次移动二格,慢指针每次移动一格最终当快指针走完时正好慢指针走完一半。
class Solution {
public ListNode middleNode(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}
Java解法2
class Solution {
public ListNode middleNode(ListNode head) {
ListNode[] A = new ListNode[100];
int t = 0;
while (head != null) {
A[t++] = head;
head = head.next;
}
return A[t / 2];
}
}
Python解法
这里的Python采用的是传统方法,先将链表存入列表中,通过索引取得列表的中间元素。
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
A = [head]
while A[-1].next:
A.append(A[-1].next)
return A[len(A) // 2]
边栏推荐
- nmap工具介绍及常用命令
- 进程和线程的退出
- [recommendation system paper reading] recommendation simulation user feedback based on Reinforcement Learning
- Vim 字符串替换
- Ml self realization / logistic regression / binary classification
- Clickhouse principle analysis and application practice "reading notes (8)
- 咋吃都不胖的朋友,Nature告诉你原因:是基因突变了
- body有8px的神秘边距
- Flutter 3.0框架下的小程序运行
- burpsuite
猜你喜欢
给刚入门或者准备转行网络工程师的朋友一些建议
SQLite3 data storage location created by Android
#797div3 A---C
leetcode 873. Length of Longest Fibonacci Subsequence | 873. 最长的斐波那契子序列的长度
图解网络:揭开TCP四次挥手背后的原理,结合男女朋友分手的例子,通俗易懂
快手小程序担保支付php源码封装
进程和线程的退出
C语言-Cmake-CMakeLists.txt教程
JVM memory and garbage collection-3-direct memory
nmap工具介绍及常用命令
随机推荐
《ClickHouse原理解析与应用实践》读书笔记(7)
Nacos microservice gateway component +swagger2 interface generation
Beaucoup d'enfants ne savent pas grand - chose sur le principe sous - jacent du cadre orm, non, ice River vous emmène 10 minutes à la main "un cadre orm minimaliste" (collectionnez - le maintenant)
Ml self realization /knn/ classification / weightlessness
Version 2.0 of tapdata, the open source live data platform, has been released
云原生应用开发之 gRPC 入门
JVM memory and garbage collection-3-runtime data area / heap area
nmap工具介绍及常用命令
Remote sensing contribution experience sharing
cv2-drawline
神经网络与深度学习-5- 感知机-PyTorch
Introduction à l'outil nmap et aux commandes communes
Tapdata 的 2.0 版 ,开源的 Live Data Platform 现已发布
Cross modal semantic association alignment retrieval - image text matching
MySQL查询为什么没走索引?这篇文章带你全面解析
The method of using thread in PowerBuilder
XXL job of distributed timed tasks
In depth analysis of ArrayList source code, from the most basic capacity expansion principle, to the magic iterator and fast fail mechanism, you have everything you want!!!
2022国内十大工业级三维视觉引导企业一览
Codeforces Round #633 (Div. 2) B. Sorted Adjacent Differences