0876. 链表的中间结点【简单】
- 本节笔记中用到的图片来源于这篇题解。
1. 📝 Description
leetcode
给你单链表的头结点 head
,请你找出并返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
示例 1:
输出:[3,4,5]
解释:链表只有一个中间结点,值为 3 。
1
2
2
示例 2:
输入:head = [1,2,3,4,5,6]
输出:[4,5,6]
解释:该链表有两个中间结点,值分别为 3 和 4 ,返回第二个结点。
1
2
3
2
3
提示:
- 链表的结点数范围是
[1, 100]
1 <= Node.val <= 100
2. 💻 题解.1 - 暴力解法 - 先找长度,再找中间
js
var middleNode = function(head) {
// 获取到链表的总长度
let len = 1,
root = head
while (head.next) {
len ++
head = head.next
}
// 找中点
for (let i = 0 i < Math.floor(len / 2) i++) {
root = root.next
}
return root
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
3. 💻 题解.2 - 快慢指针 - 一步两步
js
var middleNode = function(head) {
let slow = fast = head
while (fast.next !== null && fast.next.next !== null) {
slow = slow.next
fast = fast.next.next
}
return slow
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8