Home
DSA Patterns
Linked List
Swap Nodes in Pairs
Problem Understanding
Walk a linked list two nodes at a time and swap each pair of neighbours, then return the new head. The swap has to rewire the next pointers; copying values between nodes is not allowed.
Example: 1->2->3->4 becomes 2->1->4->3.
Attempt 1: Swapping Values
We could just iterate through the list and swap curr.val with curr.next.val. This is easy and perfectly fine in many real-world scenarios, but interviewers explicitly ban it to test your pointer manipulation skills.
Visualizing the Issue
To swap nodes A and B (prev -> A -> B -> next), we need to change 3 pointers:
prev.nextshould point toB.A.nextshould point tonext.B.nextshould point toA.
The Intuition: Iterative vs Recursive
Recursive: Swap the first two nodes, then recursively call the function for the rest of the list.
Iterative: Use a dummy node and a prev pointer to handle swaps in a loop.
Interactive Walkthrough
4 NODES · VALUES NEVER MOVE
DUMMY BEFORE HEAD
prev
dummy
→
#0
→
#1
→
#2
→
#3
→ NULL
Pairs swapped
0
dummy.next = head, and prev starts on dummy — the first pair has a node before it like every other pair
Next
prev.next (1) and prev.next.next (2) both exist — swap them
Values
Legend & Complexity
prev: the node before the pair
first
second
The swapped list returned from dummy.next
→ n: a link into another row, mid-swap
Time
O(n)
Space
O(1)
Watch the three pointer assignments that swap each pair, one step each. Values never move — every node keeps its number from the first step to the last — only next pointers change.
Dry Run Table
Input: 1 -> 2 -> 3 -> 4
| Step | prev | first | second | Action |
|---|---|---|---|---|
| Init | dummy | - | - | dummy.next = head |
| Pair 1 | dummy | 1 |
2 |
dummy.next = 2, 1.next = 3, 2.next = 1 → 2 -> 1 -> 3 -> 4 |
| Advance | 1 |
- | - | prev = first |
| Pair 2 | 1 |
3 |
4 |
1.next = 4, 3.next = NULL, 4.next = 3 → 2 -> 1 -> 4 -> 3 |
| Advance | 3 |
- | - | prev = first; prev.next is NULL, so the loop ends |
| Result | - | - | - | 2 -> 1 -> 4 -> 3 |
The Solution Template
Iterative Approach.
Swap Nodes in Pairs Code
1var swapPairs = function(head) {2 let dummy = new ListNode(0);3 dummy.next = head;4 let prev = dummy;5 while (prev.next && prev.next.next) {6 let first = prev.next;7 let second = prev.next.next;8 prev.next = second;9 first.next = second.next;10 second.next = first;11 prev = first;12 }13 return dummy.next;14};
Edge Cases & Common Mistakes
- Odd Length: The last node remains as is.
- Empty/Single Node: Return as is.
Summary
A standard pointer manipulation problem. Using a dummy node simplifies the logic for swapping the head pair.
