Open
Description
通用解法
var middleNode = function (head) {
// 统计链表的节点数
let count = 1;
let currentHead = head;
while (currentHead.next) {
count++;
currentHead = currentHead.next;
}
const middleNodeIndex = Math.floor(count / 2) + 1;
let secondHead = head;
for (let i = 1; i <= count; i++) {
if (i === middleNodeIndex) {
return secondHead
} else {
secondHead = secondHead.next
}
}
};
快慢指针
var middleNode = function(head) {
slow = fast = head;
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
};