Middle of the Linked List
You are given the values of the nodes of a singly linked list. Return the values of the middle node of the linked list, walked onward to the end. If there are two middle nodes, return the values starting from the second middle node . Use fast and slow pointers in a single pass: fast moves two steps for every one step of slow — when fast reaches the end, slow is at the middle.
Constraints
- The number of nodes in the list is in the range [1, 100].
- 1 ≤ valuesi ≤ 100
Example
values = [1, 2, 3, 4, 5][3, 4, 5]Explanation The middle node holds value 3; returning its values onward to the end gives [3, 4, 5].
In plain terms
- Linked list
- A chain of nodes where each node just points to the next one, unlike an array where all the values sit together in one contiguous block.
Fast and slow pointers find the middle in one pass
slow and fast both start at index 0 (value 1).
What happens in this step
slow = 0, fast = 0 values = [1, 2, 3, 4, 5] Both pointers start at the head. The loop condition is "while fast !== null && fast.next !== null" — fast still has a next node here, so the loop body will run.
Steps to visualize
- Point both slow and fast at the first node.
- Advance slow one step and fast two steps on each iteration.
- Stop as soon as fast reaches the last node or runs past the end.
- Slow is now at the middle node — walk onward from there to build the result.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
slow and fast both start at index 0 (value 1).
What happens in this step
slow = 0, fast = 0 values = [1, 2, 3, 4, 5] Both pointers start at the head. The loop condition is "while fast !== null && fast.next !== null" — fast still has a next node here, so the loop body will run.
Solution
function middleNode(values) {
const nodes = values.map((val) => ({ val, next: null }));
for (let i = 0; i < nodes.length - 1; i++) {
nodes[i].next = nodes[i + 1];
}
let slow = nodes[0];
let fast = nodes[0];
while (fast !== null && fast.next !== null) {
slow = slow.next;
fast = fast.next.next;
}
const result = [];
let node = slow;
while (node !== null) {
result.push(node.val);
node = node.next;
}
return result;
}- Time
- O(n)
- Space
- O(1) (excluding the constructed list and result array)
Test cases
| Input | Expected | Covers |
|---|---|---|
values = [1, 2, 3, 4, 5] | [3, 4, 5] | example from the docstring, odd length |
values = [1, 2, 3, 4, 5, 6] | [4, 5, 6] | even length returns from the second middle node |
values = [1] | [1] | smallest valid input: a single node |
values = [1, 2] | [2] | two nodes, returning from the second middle node |
values = [1, 2, 3] | [2, 3] | a short odd-length list |
values = [5, 5, 5, 5, 5] | [5, 5, 5] | every node holding the same value |