Swap Nodes in Pairs
Given the head of a linked list, swap every two adjacent nodes and return the new head. Swap the actual nodes by rewiring pointers — do not merely swap their values. If the list has an odd number of nodes, the final lone node stays in place. Empty and single-node lists are returned unchanged.
- The number of nodes is in the range [0, 100]
- 0 <= Node.val <= 100
- Solve by rewiring pointers, not by modifying node values.
head = [1,2,3,4][2,1,4,3]head = [1,2,3][2,1,3]head = [1][1]Swapping nodes in pairs is a lesson in "keeping your finger on the page." When you swap two nodes, you have to rewire three different pointers: the one before the pair, the one between them, and the one after them.
We use a Dummy Node to handle the head swap and a prev pointer to stay one step behind our swap target. In each loop, we identify the two buddies (first and second) and perform a choreographed re-linking.
dummy = Node(0, head)
prev = dummy
while prev.next and prev.next.next:
# 1. Identify Buddies
first = prev.next
second = first.next
# 2. Re-wire (The Swap)
prev.next = second
first.next = second.next
second.next = first
# 3. Jump forward 2 steps
prev = firstWe only use a handful of temporary pointers regardless of how long the list is. We are simply moving existing physical nodes around in memory like pieces on a chessboard.
Structural Node Swapping Intelligence
Phase Details
Phase 1: Foundation
We use a Dummy Node to anchor the list. This allows us to handle the head swap naturally. Prev keeps track of our position.
Think of it as a leapfrog movement. You bridge the gap between two nodes, swap them, then hop over them to the next pair.
Time Complexity: O(N) | Space Complexity: O(1). Pure link manipulation without swapping values.