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

Swap Nodes in Pairs

MediumLinked lists

You get the head of a singly linked list. Swap the first node with the second, the third with the fourth, and so on through the list. If the length is odd, the last node has no partner and stays where it is.

Do it by changing the links between nodes, not by swapping the values stored in them. Return the head of the new list.

Example 1

Input:  head = [7, 2, 9, 5]
Output: [2, 7, 5, 9]
Why:    7 and 2 trade places, then 9 and 5
2 more examples and the constraints

Example 2

Input:  head = [8, 1, 6]
Output: [1, 8, 6]
Why:    6 has no partner, so it stays last

Example 3

Input:  head = []
Output: []
Why:    an empty list has nothing to swap

Constraints

  • The list has between 0 and 100 nodes
  • 0 ≤ each node value ≤ 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. RecursionO(n)
  2. Dummy node, three links per pairO(n)

The idea in one sentence

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

Side by side

ApproachTimeRelative work for 100 nodesVerdict
RecursionO(n)
Passes; uses the call stack
Dummy node, three links per pairO(n)
Best; constant extra space

n = number of nodes. Both do the same link changes; recursion also pays for n / 2 calls.

Edge cases to test

  • Empty list. Return null; the loop never runs.
  • One node. [4] stays [4]: it has no partner.
  • Odd length. The last node keeps its place, and the node before it must still point at it.
  • Equal values. [3, 3] looks unchanged, but the nodes themselves must still trade places.

Common mistakes

  • Setting b.next = a before saving b.next, which cuts off the rest of the list.
  • Forgetting prev.next = b, so the node before the pair still points at a.
  • Swapping the values instead of the nodes, which the problem forbids.

How to talk through it

  1. 1Clarify. What happens to a last odd node? May I swap values, or must I move the nodes?
  2. 2Draw one pair. prev → a → b → next becomes prev → b → a → next: three links change.
  3. 3Add a dummy. It gives the first pair a "prev" too, so the head needs no special case.
  4. 4Code the loop. Say the order of the three assignments and why a.next must be set first.
  5. 5Test out loud. Run the empty list, one node, and an odd length before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?