Swap Nodes in Pairs Problem
Description
LeetCode Problem 24.
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Example 1:
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Example 2:
Input: head = []
Output: []
Example 3:
Input: head = [1]
Output: [1]
Constraints:
- The number of nodes in the list is in the range [0, 100].
- 0 <= Node.val <= 100
Solution
Approach: Iterative Relinking with a Dummy Head
Since only the links may change, each swap rewires three pointers. We keep prev, the node just before the pair being swapped; a dummy node in front of head plays that role for the first pair, so the new head needs no special case.
While at least two nodes follow prev:
- Name them
first = prev.nextandsecond = first.next. - Rewire
prev -> first -> second -> restintoprev -> second -> first -> rest:first.next = second.next(first now points to the rest of the list),second.next = first,prev.next = second.
- After the swap,
firstis the node just before the next pair, so setprev = first.
dummy -> 1 -> 2 -> 3 -> 4
dummy -> 2 -> 1 -> 3 -> 4 prev = 1
dummy -> 2 -> 1 -> 4 -> 3 prev = 3, fewer than two nodes left: stop
The order of the three assignments matters: first.next has to take second.next before second.next is overwritten, or the rest of the list is lost. A leftover single node at the end (odd length) is left where it is, because the loop needs two nodes to continue.
Complexity: O(n) time, where n is the number of nodes, and O(1) extra space.
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(0, head) # node before the first pair, so the head needs no special case
prev = dummy # node just before the next pair to swap
while prev.next and prev.next.next:
first = prev.next
second = first.next
# prev -> first -> second -> rest becomes prev -> second -> first -> rest
first.next = second.next
second.next = first
prev.next = second
prev = first # first is now the node just before the next pair
return dummy.next
Now write it from memory
Close the write-up and solve it yourself against the tests.