AAlgoLoopSpaced repetition for LeetCode
MEDIUMLinked ListLeetCode ↗

Swap Nodes in Pairs

The key idea

Swap each adjacent pair by rewiring the three next pointers around it — never by copying values. A dummy node placed before the head gives the very first pair a stable predecessor, so every pair (including the first) is rewired by the same uniform code with no special case.

Problem

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 the nodes themselves may be changed). Each adjacent pair, such as the nodes holding 1 and 2, is reordered so the second comes first. If the list has an odd number of nodes, the final unpaired node keeps its position.

Constraints

Examples

Input: head = [1,2,3,4] Output: [2,1,4,3]
Input: head = [] Output: []
Input: head = [1] Output: [1]

Complexity

Time: O(n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Linked List problems