AlgoInsight

DSA problem

Swap Nodes in Pairs

MediumLinked ListPattern: Linked Listtop75FreeAmazonMicrosoftFacebookBloombergApple

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values stored in the list's nodes — that is, only the node pointers themselves may be changed.

If the list has an odd number of nodes, the final lone node stays in place because it has no partner to swap with. The relative order of every pair is reversed, but the pairs themselves keep their original sequence relative to one another.

The classic pitfall is the head of the list: after the first swap the second node becomes the new head, so a simple loop that returns the original head would be wrong. A dummy node placed before the head elegantly removes this special case, because the dummy's next pointer always tracks the true head as it changes.

The intuition is to keep a prev pointer that sits just before each pair. For every pair of nodes (call them first and second), we rewire three links: prev.next points to second, first.next points to whatever follows second, and second.next points back to first. Then we advance prev to first (now the tail of the swapped pair) and repeat. This processes the list in a single pass with constant extra space.

Examples

Example 1
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Explanation: The pair (1,2) is swapped to (2,1) and the pair (3,4) is swapped to (4,3), producing [2,1,4,3].
Example 2
Input: head = [1,2,3]
Output: [2,1,3]
Explanation: The pair (1,2) is swapped to (2,1). The node 3 has no partner, so it remains unchanged at the end.
Example 3
Input: head = []
Output: []
Explanation: An empty list has no nodes to swap, so the result is an empty list.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

linked-listrecursionin-placepointers

Browse all DSA problems