Swap Nodes in Pairs
Difficulty: Medium · Pattern: Linked List · LeetCode #24
Swap every two adjacent nodes and return the head. Change the nodes' links, not their values.
Examples
text
1 → 2 → 3 → 4 → 2 → 1 → 4 → 3
1 → 1
1 → 2 → 3 → 2 → 1 → 3Hints
- Use a dummy node before the head;
prevpoints at the node before the current pair. - For each pair (a, b): prev.next = b, a.next = b.next, b.next = a.
Approach
With prev = dummy, while there are two nodes a = prev.next and b = a.next: rewire prev.next = b, a.next = b.next, b.next = a, then prev = a. The dummy handles the head change uniformly. O(n).
Complexity
Time: O(n). Space: O(1).
Python solution
def swapPairs(head):
dummy = ListNode(0, head)
prev = dummy
while prev.next and prev.next.next:
a, b = prev.next, prev.next.next
prev.next, a.next, b.next = b, b.next, a
prev = a
return dummy.nextJavaScript solution
function swapPairs(head) {
const dummy = new ListNode(0, head); let prev = dummy;
while (prev.next && prev.next.next) {
const a = prev.next, b = a.next;
prev.next = b; a.next = b.next; b.next = a; prev = a;
}
return dummy.next;
}