15% off all plans & roadmaps Use code
See plansLeetCode 24 · Solution & editorial
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.)
Swap Nodes in Pairs is a Linked List Manipulation Patterns problem, in the Reordering / Partitioning subpattern. The pattern covers in-place reversal, merging sorted lists, reordering, and intersection detection
Learn to reorder and partition linked lists. Master techniques like swap pairs, rotate list, and odd-even separation.
The reference solution runs in O(n) time and O(1) space.
Swap Nodes in Pairs has been reported in interviews at Microsoft, Amazon, Facebook, Google, eBay, ByteDance.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Swap Nodes in Pairs is a Linked List Manipulation Patterns problem, in the Reordering / Partitioning subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.