Swap Nodes in Pairs
Medium
Topics
Given the head of a linked list, swap every two adjacent nodes and return its head. You must swap the nodes themselves, not just their values. A trailing odd node stays in place.
Example 1
Input: head = [1,2,3,4] Output: [2,1,4,3]
Example 2
Input: head = [1,2,3] Output: [2,1,3]
Constraints
- 0 <= number of nodes <= 100
- 0 <= Node.val <= 100
Editorial — intuition, approach, complexity and pitfalls
Intuition
Swapping adjacent nodes means rewiring three links per pair, and the node that has to change is the one before the pair — which for the first pair is the head itself. A dummy node in front makes every pair look identical and removes the special case.
Keep prev at the node preceding the pair. Name the pair a and b, then write the three links: a jumps over b, b points back at a, and prev points at b. Afterwards a is the node preceding the next pair, so it becomes the new prev.
Approach
- Create a dummy whose
nextis the head; setprevto it. - While
prev.nextandprev.next.nextboth exist, takea = prev.nextandb = a.next. - Rewire:
a.next = b.next, thenb.next = a, thenprev.next = b. - Set
prev = aand continue. - Return
dummy.next.
Dry Run
input 1 -> 2 -> 3 -> 4
pair (1,2) a=1 b=2
a.next = b.next 1 -> 3
b.next = a 2 -> 1
prev.next = b dummy -> 2
prev = a prev is now 1
pair (3,4) a=3 b=4 same three writes
answer 2 -> 1 -> 4 -> 3
[1,2,3] -> 2 -> 1 -> 3 the odd tail stays put
[1] -> 1
[] -> emptyComplexity
- Time — O(n): each pair is handled once with constant work.
- Space — O(1): a dummy and three pointers. The recursive formulation is equally short but costs O(n) frames, which the iterative version avoids.
Common Pitfalls
- Swapping the values instead of the nodes. The problem forbids it explicitly, and it is the first thing an interviewer checks for.
- Testing only
prev.next. Bothprev.nextandprev.next.nextmust exist, or the last odd node is dereferenced through a null. - Writing the three links in the wrong order.
a.nextmust be read frombbeforeb.nextis overwritten, otherwise the rest of the list is lost. - Advancing
prevtob. After the swap,ais the trailing node of the pair, so it is the one preceding the next pair. - Working without a dummy and then special-casing the head. It is doable and it roughly doubles the code.
- Reversing the whole list in pairs of values and calling it done when the list has odd length. The trailing node must be left alone, which the loop condition handles for free.
Full Solution — all languages
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def swapPairs(self, head):
dummy = ListNode(0, head)
prev = dummy
while prev.next and prev.next.next:
a = prev.next
b = a.next
a.next = b.next
b.next = a
prev.next = b
prev = a
return dummy.nextimport java.util.*;
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy;
while (prev.next != null && prev.next.next != null) {
ListNode a = prev.next, b = a.next;
a.next = b.next;
b.next = a;
prev.next = b;
prev = a;
}
return dummy.next;
}
}#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x): val(x), next(nullptr) {
}
};
class Solution {
public: ListNode* swapPairs(ListNode* head) {
ListNode dummy(0);
dummy.next = head;
ListNode* prev = &dummy;
while (prev->next && prev->next->next) {
ListNode* a = prev->next;
ListNode* b = a->next;
a->next = b->next;
b->next = a;
prev->next = b;
prev = a;
}
return dummy.next;
}
};/** Node shape: { val, next }. Build/return plain objects or use this ctor. */ function ListNode(val, next) {
this.val = (val === undefined ? 0 : val);
this.next = (next === undefined ? null : next);
}
/**
* @param {ListNode} head
* @return {ListNode}
*/ var swapPairs = function(head) {
const dummy = new ListNode(0, head);
let prev = dummy;
while (prev.next && prev.next.next) {
const a = prev.next, b = a.next;
a.next = b.next;
b.next = a;
prev.next = b;
prev = a;
}
return dummy.next;
};