# 876.链表的中间结点
给定一个头结点为 head
的非空单链表,返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。
# 解答
- 利用数组存储值
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var middleNode = function(head) {
if(!head) return []
let result = []
while(head) {
result.push(head)
head = head.next
}
return result[Math.floor(result.length / 2)]
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
- 利用双指针,快指针走两步,慢指针走一步,快指针走完,慢指针则为中间值
var middleNode = function (head) {
if (!head) return []
var fast = slow = head
while (fast && fast.next) {
slow = slow.next
fast = fast.next.next
}
return slow
};
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9