Swap Nodes in Pairs

MediumLinked List · Pointer Rewiring🧩 Linked List TechniquesLeetCode #24 ↗Updated

Problem

Walk a singly linked list two nodes at a time and exchange each neighbouring pair (1st↔2nd, 3rd↔4th, …); a trailing odd node stays put. Return the new head. You must move the nodes themselves — editing val fields is not allowed.
Input[1,2,3,4]Output[2,1,4,3]
Input[1,2,3]Output[2,1,3]
Input[]Output[]

0 ≤ number of nodes ≤ 100  ·  0 ≤ Node.val ≤ 100  ·  Values must not be modified.

Try it yourself

Java
class Solution {
    public ListNode swapPairs(ListNode head) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Swapping a pair prev → a → b → next is just three pointer writes: a.next = next, b.next = a, prev.next = b. A dummy node gives the first pair a prev too.
PatternLinked List Techniques

Instinct Nodes joined by next pointers and the task is to reverse, splice, merge, reorder or remove in place - grab a dummy head and rewire pointers carefully.

Memory hack Save next, flip, step - never let go of a rope before you've grabbed the next one.

Open the Linked List Techniques guide →

Approaches

Brute ForceArray of Nodes, Swap, Relink

Time O(n)Space O(n)

Copy node references into a list, swap entries i and i+1 for every even i, then relink the nodes in their new order and terminate the last one. Easy, since arrays allow random access.

Java
public ListNode swapPairs(ListNode head) {
    List<ListNode> nodes = new ArrayList<>();
    for (ListNode c = head; c != null; c = c.next) nodes.add(c);
    for (int i = 0; i + 1 < nodes.size(); i += 2) Collections.swap(nodes, i, i + 1);
    for (int i = 0; i < nodes.size(); i++) {
        nodes.get(i).next = (i + 1 < nodes.size()) ? nodes.get(i + 1) : null;
    }
    return nodes.isEmpty() ? null : nodes.get(0);
}

Simple and safe, but O(n) extra memory for something pointers can do in place.

At a glance

LevelApproachTimeSpace
Brute ForceArray of Nodes, Swap, RelinkO(n)O(n)
BetterRecursionO(n)O(n)
OptimalIterative with Dummy NodeO(n)O(1)
Common pitfalls
  • Swapping vals instead of nodes — explicitly disallowed.
  • Writing prev.next = second first without saving second.next — loses the rest of the list.
  • Advancing prev to second — after the swap the pair's tail is first.
Interview tips
  • Draw prev → a → b → next and list the three writes before coding.
  • Test empty, single-node and odd-length lists out loud.
  • Generalise: this is Reverse Nodes in k-Group with k = 2.
Pattern
Dummy head + local rewiring → in-place reordering of small groups of linked-list nodes.
My notes saved in this browser