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

Delete the Middle Node of a Linked List

MediumLinked lists

A singly linked list starts at head and holds n nodes. Count positions from 0 at the head. The middle node is the one at position ⌊n / 2⌋: with 4 nodes it is position 2, with 5 nodes it is also position 2.

Cut that one node out of the list and hand back the first node of what remains. A list with one node becomes empty.

Example 1

Input:  head = [5, 8, 2, 9, 4, 6]
Output: [5, 8, 2, 4, 6]
Why:    6 nodes, so position 3 (the 9) goes
2 more examples and the constraints

Example 2

Input:  head = [6, 1, 8, 3, 5]
Output: [6, 1, 3, 5]
Why:    5 nodes, so position 2 (the 8) goes

Example 3

Input:  head = [4]
Output: []
Why:    the only node is the middle one

Constraints

  • 1 ≤ number of nodes ≤ 100,000
  • 1 ≤ each node value ≤ 100,000

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 walkO(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

ApproachTimeNode visits for 100,000 nodesVerdict
Count, then walkO(n)
Passes; walks one and a half times
Fast and slow pointersO(n)
Best; one pass, no count

n = number of nodes. Both are linear; the second avoids the counting pass.

Edge cases to test

  • One node. [4] has middle position 0, so the answer is an empty list.
  • Two nodes. [3, 7] has middle position 1: the 7 goes and [3] is left.
  • Even length. With 6 nodes the middle is position 3, the later of the two centre nodes.
  • Odd length. With 5 nodes the middle is position 2, the true centre.

Common mistakes

  • Stopping slow on the middle itself, then having no way to reach the node before it.
  • Forgetting the one-node list, where head.next.next would read past the end.
  • Picking the earlier centre node for even lengths. The rule is position ⌊n / 2⌋, the later one.

How to talk through it

  1. 1Clarify. For an even length, which centre node is the middle? What do I return for a single node?
  2. 2Give the simple way. Count the nodes, then walk to the one before position n / 2. Two passes, O(1) space.
  3. 3Find the middle in one pass. A pointer moving twice as fast reaches the end when the slow one is halfway.
  4. 4Code it with the head start. Start fast two nodes ahead so slow stops one before the middle.
  5. 5Test out loud. Run one node, two nodes, and an odd and an even length.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?