LeetCode 24 · Linked list

Swap Nodes in Pairs, explained with a picture

Swapping coaches two at a time.

Linked list
▶ Watch it step by step

The problem

Swap every two adjacent nodes in a linked list (1↔2, 3↔4, …) by changing links, not values.

Input:  1 → 2 → 3 → 4 → 5
Output: 2 → 1 → 4 → 3 → 5

Picture it

Picture a shunting yard swapping pairs of neighbouring coaches. A marker stands before each pair; we re-couple the second coach in front of the first, connect the pair back to the train, and move the marker two coaches on.

Short version: the full lesson (brute force, complexity, edge cases and a quiz) is still being written. The animation is complete.

The key idea

Rewire three pointers per pair, using a dummy head. O(n).

Python solution

def swap_pairs(head):
    dummy = prev = Node(0, head)
    while prev.next and prev.next.next:
        a, b = prev.next, prev.next.next
        prev.next, a.next, b.next = b, b.next, a
        prev = a
    return dummy.next

In the interactive version each line lights up as the animation runs, and you can type your own input to see the algorithm handle it.