Swap Nodes in Pairs

Swap every two neighbouring nodes of a linked list by changing their links, not their values.

Given the head of a linked list, swap every two neighbouring nodes and return the head of the changed list. Only the links between the nodes may change, not the values stored in them. If the list has an odd number of nodes, the last node has no partner and stays where it is.

Example 1
Input: head = [1, 2, 3, 4]
Output: [2, 1, 4, 3]
Example 2
Input: head = [1, 2, 3]
Output: [2, 1, 3]
Explanation: 1 and 2 swap places, and 3 has no partner, so it stays last.
Solution

The Idea

Picture people standing in a queue where each person only knows who stands right behind them. A linked list works the same way. Every node keeps its value and a link named next that points one place along the queue. The first node is the head, and the last node's next is null, meaning nothing follows.

Take Example 1, [1, 2, 3, 4]. The pairs are 1 and 2, then 3 and 4, and swapping each pair gives [2, 1, 4, 3]. Writing new values into the nodes would be easy, but the problem forbids it, so the nodes themselves must change places. Which links have to change when two nodes swap?

Look at the picture below. It shows Example 1 halfway through, with the first pair already swapped: 2, 1, 3, 4. The next pair is 3 and 4. Call the first node of the pair a, the second b, and the node just before the pair prev.

The list 2, 1, 3, 4 with prev on 1, a on 3 and b on 4. After the swap it reads 2, 1, 4, 3: a points to what came after b, here null, b points to a, and prev points to b.

In the row labelled before, prev (1) points to a (3), a points to b (4), and b points to null. In the row labelled after, three links have changed, drawn in orange. The link labelled 1: a → after b makes 3 point to whatever followed 4, here null. The link labelled 2: b → a makes 4 point back to 3, and the link labelled 3: prev → b makes 1 point to 4.

So swapping a pair always means changing three links, and the rest of the list is not touched. The order matters too. Until link 1 is set, only b knows where the rest of the list continues. If b were pointed back at a first, that rest of the list would be lost.

Solution Approach

Turning those three link changes into a loop over the whole list means settling three things: what plays prev for the first pair, when to stop, and how to move on to the next pair.

A node in front of the head

What is prev for the first pair? In [1, 2, 3, 4] nothing comes before 1, and swapping 1 and 2 changes which node is the head. A special case for the first pair would work, but it repeats the link changes. Simpler is an extra node, made only for this purpose and placed in front of the head. Such a node is called a dummy node.

The dummy node's next is the head, so it plays prev for the first pair, and the first swap is no different from any other. Whatever ends up first in the list, the dummy node points to it, so after the last swap dummy.next is the new head.

When to stop

How do we know a full pair is still left? The pair starts right after prev, so both prev.next and prev.next.next must exist. In Example 2, [1, 2, 3], after the first swap prev is on 1, and only 3 follows it. The check fails, so 3 stays last. For an empty list or a single node, the check fails before any swap.

Moving to the next pair

Which node is prev for the next pair? It must be the node just before that pair, which is the last node of the pair just swapped. Since a and b changed places, that node is a. So prev moves to a, two nodes further along than before.

Java Solution

The method swapPairs works in these steps:

  1. First, create the dummy node with new ListNode(0, head), so its next is the head. Its value, 0, is never read. Set prev to dummy.
  2. Loop while prev.next and prev.next.next are both not null, so a full pair follows prev.
  3. Inside the loop, name the pair: a is prev.next and b is a.next.
  4. Change the three links in order: a.next = b.next, then b.next = a, then prev.next = b.
  5. Move prev to a, the second node of the swapped pair.
  6. When the loop ends, return dummy.next, the new head.

The class also has a small ListNode class, a build helper that makes a list from numbers, and a show helper that prints a list in the same form as the examples. The main method runs both examples, a list of six nodes, a single node and an empty list.

Java
public class SwapNodesInPairs {

    static class ListNode {
        int val;
        ListNode next;
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    public static ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(0, head);
        ListNode prev = dummy;
        while (prev.next != null && prev.next.next != null) {
            ListNode a = prev.next;
            ListNode b = a.next;
            a.next = b.next;   // a skips ahead to the node after the pair
            b.next = a;        // b now comes before a
            prev.next = b;     // the node before the pair now leads to b
            prev = a;          // a is the second node of the swapped pair
        }
        return dummy.next;
    }

    static ListNode build(int... values) {
        ListNode head = null;
        for (int i = values.length - 1; i >= 0; i--) {
            head = new ListNode(values[i], head);
        }
        return head;
    }

    static String show(ListNode head) {
        StringBuilder sb = new StringBuilder("[");
        for (ListNode n = head; n != null; n = n.next) {
            sb.append(n.val).append(n.next != null ? ", " : "");
        }
        return sb.append("]").toString();
    }

    public static void main(String[] args) {
        System.out.println(show(swapPairs(build(1, 2, 3, 4))));
        System.out.println(show(swapPairs(build(1, 2, 3))));
        System.out.println(show(swapPairs(build(1, 2, 3, 4, 5, 6))));
        System.out.println(show(swapPairs(build(7))));
        System.out.println(show(swapPairs(build())));
    }
}

Running it prints:

Output
[2, 1, 4, 3]
[2, 1, 3]
[2, 1, 4, 3, 6, 5]
[7]
[]

Example 1 gives [2, 1, 4, 3], and Example 2 gives [2, 1, 3], with 3 left alone because it has no partner. In [2, 1, 4, 3, 6, 5], three pairs are swapped in turn, with prev moving two nodes each time. The single node [7] and the empty list [] come back unchanged, because the loop check fails before any swap.

Moving prev to b instead of a is an easy slip, since prev.next was just set to b. With that one change, Example 1 prints [2, 3, 4, 1]. After the first swap, prev sits on 2, so 1 and 3 are taken as the next pair, and 1 keeps being swapped one place further back.

Complexity

The method walks the list once and does a fixed amount of relinking for each pair.

  • Time: O(n), for a list of n nodes: each loop pass swaps one pair with three link changes and moves prev two nodes forward, so the loop runs about n / 2 times.
  • Space: O(1). Besides the one dummy node, the method keeps only the references prev, a and b, and it reuses the existing nodes instead of building a new list.

Swapping pairs is reversing the list in groups of two. For groups of any size, see Reverse Nodes in k-Group.