Swap Nodes in Pairs

Med
Concept
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Swap Nodes in Pairs

Approach

Use a dummy node before the head. Walk through the list with a prev pointer. For each pair (first, second), rewire: prev.next = second, first.next = second.next, second.next = first. Advance prev to first (which is now the second node in the swapped pair).

Complexity Analysis

Time
O(n)
Space
O(1)

Pattern

Linked List (Pointer Manipulation)

Why It Works

A dummy node simplifies head swaps. Each pair swap only needs three pointer reassignments. The prev pointer ensures the preceding node always links to the new front of each swapped pair.

Updated Feb 2026