Swap Nodes in Pairs (LeetCode 24): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Create
dummypointing atheadand setprev = dummy. - Loop while
prev.nextandprev.next.nextboth exist, meaning a full pair remains. - Name the pair:
first = prev.nextandsecond = prev.next.next. - Set
prev.next = secondso the predecessor now leads to the second node. - Set
first.next = second.nextso the pair stays attached to the rest of the list, then setsecond.next = firstto finish the swap. - Move
prevtofirst, which is now the tail of the swapped pair, and continue. Returndummy.nextat the end.
Step-by-step example
head = [1,2,3,4]
- The list starts as dummy → 1 → 2 → 3 → 4 with
prevat the dummy. - The first pair is 1 and 2. After rewiring, dummy → 2 → 1 → 3 → 4, and
prevmoves to node 1. - 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. prevmoves 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.next1class Solution {
2 public ListNode swapPairs(ListNode head) {
3 ListNode dummy = new ListNode(0, head);
4 ListNode prev = dummy;
5
6 while (prev.next != null && prev.next.next != null) {
7 ListNode first = prev.next;
8 ListNode second = prev.next.next;
9
10 prev.next = second;
11 first.next = second.next;
12 second.next = first;
13 prev = first;
14 }
15
16 return dummy.next;
17 }
18}1class Solution {
2public:
3 ListNode* swapPairs(ListNode* head) {
4 ListNode dummy(0, head);
5 ListNode* prev = &dummy;
6
7 while (prev->next && prev->next->next) {
8 ListNode* first = prev->next;
9 ListNode* second = prev->next->next;
10
11 prev->next = second;
12 first->next = second->next;
13 second->next = first;
14 prev = first;
15 }
16
17 return dummy.next;
18 }
19};Time and space complexity
O(n)
Each iteration handles two nodes with a constant number of pointer updates, so the list is walked once.
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 = firstbefore savingsecond.next. The link to the rest of the list is lost unlessfirst.next = second.nextruns first. - Forgetting to update
prev.next, which leaves the previous pair pointing at the old first node. - Moving
prevtosecondinstead offirst. After the swap,firstis the tail of the pair, so moving tosecondswaps the wrong nodes next time. - Returning
headinstead ofdummy.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.