Swap Nodes in Pairs
Swap adjacent nodes in a linked list pairwise by altering node link pointers recursively.
01The problem
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).
| Input | Output | Why |
|---|---|---|
[1, 2, 3, 4] | [2, 1, 4, 3] | Pair (1, 2) swapped to (2, 1); pair (3, 4) swapped to (4, 3) |
[] | [] | Empty list remains empty |
[1] | [1] | Single node has no partner to swap with |
[1, 2, 3] | [2, 1, 3] | Trailing odd node 3 remains in place |
Constraints: Number of nodes in the list is in the range [0, 100], 0 <= Node.val <= 100.
Loading the rest of the lesson…