mediumLinked ListLinked List

Swap Nodes in Pairs

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

Recognize the pattern

swap pairs of adjacent nodespointer manipulation not value swapdummy head helps

Brute force idea

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

Better approach

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.

Key invariant

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

Watch out for

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

Linked List Pattern