Problem Statement

Swap Nodes in Pairs

You are given a linked list. A linked list is a chain of boxes, where each box is called a node. A node holds a value and a pointer, which is just an arrow that points to the next node in the chain. To get from one node to the next, you follow that arrow. Your job is to swap every two neighbors in the chain. So 1 and 2 trade places, 3 and 4 trade places, and so on. The catch is that you must move the nodes themselves by re-pointing the arrows. You are not allowed to just copy the numbers between nodes. Re-pointing arrows is called pointer manipulation, and the trick that makes it clean is a dummy node, which is a fake extra node we glue to the very front so that swapping the first pair works the same way as swapping any other pair.

mediumLinked ListLinked ListTime: 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.

Trace it on head=[1,2,3,4]

init: dummy->1->2->3->4, prev=dummy
iter1: A=1, B=2 (prev.next & prev.next.next exist)
iter1 relink: 1.next=3, 2.next=1, prev.next=2 => dummy->2->1->3->4
iter1 advance: prev=node1
iter2: A=3, B=4; relink: 3.next=null, 4.next=3, prev.next=4 => dummy->2->1->4->3
iter2 advance: prev=node3
iter3: prev.next=null => loop stops
return dummy.next = 2->1->4->3

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.

Shape of the loop

dummy -> head; prev = dummy
while prev.next and prev.next.next:
    A, B = prev.next, prev.next.next
    A.next = B.next; B.next = A; prev.next = B
    prev = A          # A is now 2nd in pair, advance by 2
return dummy.next

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

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

Linked List Pattern