Swap Nodes in Pairs (LeetCode 24): Solution and Explanation

Medium
Linked List
Recursion

Given a singly linked list, swap every two adjacent nodes and return the new head. If the list has an odd length, the last node stays where it is. You must rearrange the nodes themselves rather than swapping their values.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Swapping values would be trivial, but the problem forbids it, so the real task is relinking nodes. For one pair, A then B, you need the node before the pair to point to B, B to point to A, and A to point to whatever came after B. Three pointer changes per pair, done in the right order so nothing gets lost.

The awkward part is the very first pair, which has no node before it, so its swap would also have to update the head. A dummy node in front of the list removes that special case: every pair, including the first, now has a predecessor prev, and the real head is always dummy.next at the end.

From there the loop is mechanical. While there are at least two nodes after prev, call them first and second. Point prev.next to second, point first.next to the node after second, and point second.next back to first. After the swap, first has become the second node of the pair, so it is the predecessor of the next pair, and prev moves to it.

A useful habit for any linked list rewiring is to draw the four nodes involved (predecessor, first, second and the node after second) and write the new arrows before touching code. Once you can see which old link must be read before it is overwritten, the order of the three assignments follows naturally, and the same drawing helps for harder variants like reversing nodes in groups of k.

Approach: Iterative pointer rewiring with a dummy node

  1. Create dummy pointing at head and set prev = dummy.
  2. Loop while prev.next and prev.next.next both exist, meaning a full pair remains.
  3. Name the pair: first = prev.next and second = prev.next.next.
  4. Set prev.next = second so the predecessor now leads to the second node.
  5. Set first.next = second.next so the pair stays attached to the rest of the list, then set second.next = first to finish the swap.
  6. Move prev to first, which is now the tail of the swapped pair, and continue. Return dummy.next at the end.

Step-by-step example

head = [1,2,3,4]
  1. The list starts as dummy → 1 → 2 → 3 → 4 with prev at the dummy.
  2. The first pair is 1 and 2. After rewiring, dummy → 2 → 1 → 3 → 4, and prev moves to node 1.
  3. The next pair is 3 and 4. prev.next (node 1) becomes 4, node 3 points at null, and node 4 points at 3, giving dummy → 2 → 1 → 4 → 3.
  4. prev moves to node 3, which has no next node, so the loop ends and the function returns [2,1,4,3].

Code: Python, Java, C++

1class Solution:
2    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
3        dummy = ListNode(0, head)
4        prev = dummy
5
6        while prev.next and prev.next.next:
7            first = prev.next
8            second = prev.next.next
9
10            prev.next = second
11            first.next = second.next
12            second.next = first
13            prev = first
14
15        return dummy.next

Time and space complexity

Time

O(n)

Each iteration handles two nodes with a constant number of pointer updates, so the list is walked once.

Space

O(1)

Only the dummy node and a few pointers are used; nodes are relinked in place.

Other approaches

Recursion (time O(n), space O(n))

Swap the first two nodes, then set the original first node's next to the result of recursively swapping the rest of the list. It is very short but uses O(n) stack space for the recursion.

Common mistakes

  • Setting second.next = first before saving second.next. The link to the rest of the list is lost unless first.next = second.next runs first.
  • Forgetting to update prev.next, which leaves the previous pair pointing at the old first node.
  • Moving prev to second instead of first. After the swap, first is the tail of the pair, so moving to second swaps the wrong nodes next time.
  • Returning head instead of dummy.next. The original head is now the second node, so returning it drops the new first node.

Frequently asked questions

Why use a dummy node in Swap Nodes in Pairs?

The first swap changes the head of the list. A dummy node gives the first pair a predecessor like every other pair, so the loop needs no special case and the new head is simply dummy.next.

Can I just swap the values?

The problem asks you to change the links, not the values. Swapping values would pass simple tests but is not considered a valid solution, and in real systems nodes may carry data that cannot be copied cheaply.

What happens with an odd number of nodes?

The loop needs two nodes after prev. With one node left, the condition fails and that final node stays in place.

Recursive or iterative, which is better?

Both run in O(n) time. The iterative version uses O(1) extra space, while recursion uses O(n) stack frames, so iteration is safer for long lists.