Overview
Given the head of a singly linked list, return the middle node. If there are two middle nodes, return the second one.
Constraints
- The number of nodes is in the range
[1, 100]. 1 <= Node.val <= 100
Examples
middleNode([1, 2, 3, 4, 5]); // => [3, 4, 5] (middle is node 3) middleNode([1, 2, 3, 4, 5, 6]); // => [4, 5, 6] (second middle)
Solution
Reveal solution
function middleNode(head) {
let slow = head, fast = head;
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}Resources
middle-of-linked-list.js
Middle of the Linked List
easycodingAlgorithmsLinked Lists
Overview
Given the head of a singly linked list, return the middle node. If there are two middle nodes, return the second one.
Constraints
- The number of nodes is in the range
[1, 100]. 1 <= Node.val <= 100
Examples
middleNode([1, 2, 3, 4, 5]); // => [3, 4, 5] (middle is node 3) middleNode([1, 2, 3, 4, 5, 6]); // => [4, 5, 6] (second middle)
Solution
Reveal solution
function middleNode(head) {
let slow = head, fast = head;
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}Resources
NameTopicDifficulty
103 of 103 problems