Skip to content
Problem 876 · LeetCode 876(opens in a new tab)

Middle of the Linked List

EasyLinked lists

You get head, the first node of a singly linked list. Return the node that sits in the middle of the list.

When the list has an even number of nodes there are two middle nodes; return the later of the two. The answer is the node itself, so it is shown as the list that starts there.

Example 1

Input:  head = [7, 3, 9, 2, 5]
Output: [9, 2, 5]
Why:    9 has two nodes before it and two after
2 more examples and the constraints

Example 2

Input:  head = [8, 1, 6, 4]
Output: [6, 4]
Why:    1 and 6 are both central; take the second, 6

Example 3

Input:  head = [5]
Output: [5]
Why:    a single node is its own middle

Constraints

  • The list holds between 1 and 100 nodes
  • Every node value is between 1 and 100

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Count, then walk halfwayO(n)
  2. Fast and slow pointersO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative pointer moves for 100 nodesVerdict
Count, then walk halfwayO(n)
Passes; two passes
Fast and slow pointersO(n)
Best; one pass

n = number of nodes. Both make about 1.5n pointer moves; the second makes them in a single pass, without knowing the length first.

Edge cases to test

  • One node. [5]: fast.next is null at once, so slow stays on the head.
  • Two nodes. [1, 2]: both are central, and the answer is the second, [2].
  • Even length. [8, 1, 6, 4] returns the node 6, the later of the two middles.
  • Odd length. [7, 3, 9, 2, 5] returns 9, with two nodes on each side.

Common mistakes

  • Looping on fast.next and fast.next.next, which returns the first middle on even lengths.
  • Checking only fast.next and then reading fast.next.next when fast is already null.
  • Returning the value instead of the node; the caller expects the rest of the list from there.

How to talk through it

  1. 1Clarify. With an even count, do you want the first or the second middle? Is the list ever empty?
  2. 2Give the simple version. Count the nodes, then walk n // 2 steps from the head.
  3. 3Make it one pass. A pointer moving twice as fast reaches the end when the slow one is halfway.
  4. 4Code the loop. While fast and fast.next exist, slow takes one step and fast takes two; return slow.
  5. 5Test out loud. Run one node, two nodes and a five-node list.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?