Medium · Pointer Rewiring
Understand → Visualise → Practice.
Nodes are represented by their values in traversal order. Return the order after swapping every adjacent node pair.
For each pair (first, second), point prev to second, second to first, and first to the node after the pair. Then move prev to first.
prev = dummy, so the first pair is handled like any other.
first = prev.next, second = first.next; set prev.next = second, first.next = second.next, second.next = first.
Set prev = first and repeat while two nodes remain; an odd last node stays put.
O(n) time and O(1) extra space.
Changing pointers in the wrong order loses the rest of the list; save first and second before relinking.
Read the full guide first: Linked Lists.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.