Middle of the Linked List

Easy#876middle

You get the head of a linked list. Return its middle node. When the length is even there are two middle nodes, and the answer is the second of them. Our example: 5 → 2 → 7 → 4 → 9 → 1 → 6 → 3, eight nodes — the middle nodes are 4 and 9, so the answer is the node 9.

input
head: the head of a linked list of n nodes.
returns
The middle node of the list; when n is even there are two middle nodes, and the answer is the second. It is printed as the list from it to the end.
constraints
  • 1 ≤ n ≤ 100
  • 1 ≤ Node.val ≤ 100
our 13 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
function middleNode(head) {

}
Ctrl ↵
format
reset

saved in this browser

13 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more fast and slow pointers problems

Pattern “Fast and slow pointers” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.