Browse Curriculum
Linked List
Medium

Swap Nodes in Pairs

Swap every two adjacent nodes.

Problem Understanding

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed).

Example: 1->2->3->4 becomes 2->1->4->3.

Attempt 1: Swapping Values

We could just iterate through the list and swap curr.val with curr.next.val. This is easy and perfectly fine in many real-world scenarios, but interviewers explicitly ban it to test your pointer manipulation skills.

Visualizing the Issue

To swap nodes A and B (prev -> A -> B -> next), we need to change 3 pointers:

  1. prev.next should point to B.
  2. A.next should point to next.
  3. B.next should point to A.

The Intuition: Iterative vs Recursive

Recursive: Swap the first two nodes, then recursively call the function for the rest of the list.
Iterative: Use a dummy node and a prev pointer to handle swaps in a loop.

Interactive Walkthrough

Step 1 / 1
Empty List

Initializing...

1x

Watch how the pointers are re-wired to swap nodes.

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.