mediumLinked ListLinked List

Swap Nodes in Pairs

mediumTime: O(n)Space: O(1)

Signals to notice

swap pairs of adjacent nodespointer manipulation not value swapdummy head helps

Brute force first

Swap values — works but violates the constraint of changing pointers only.

The key insight

Dummy head → for each pair (A,B): prev.next = B, A.next = B.next, B.next = A. Advance prev by 2. O(n) time, O(1) space.

What must stay true

Three pointers per swap: prev, A, B. After relinking: prev→B→A→rest. The dummy head handles swapping the first pair without special logic.

Easy way to go wrong

Losing references — save B.next before relinking. Draw the before/after state to verify.

Linked List Pattern