Pairwise Swap Nodes in a Linked List
Implement swapPairs
Given the head of a singly linked list, swap every two adjacent nodes and return the new head. Nodes must actually be relinked, not just have their values swapped — a leftover single node (odd-length list) stays exactly where it is.
The optimal solution anchors a
prev pointer right before each pair with a dummy node, exactly the same idea used to reverse any run of nodes: relink first.next, second.next, and prev.next in a fixed three-line sequence so second ends up leading and first trails right behind it, then slide prev up to first — now the trailing node of the pair just swapped — before repeating for the next pair.
Example 1:
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Example 2:
Input: head = []
Output: []
Example 3:
Input: head = [1]
Output: [1]
+ 5 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ number of nodes in head ≤ 200 - ●
-1000 ≤ node value ≤ 1000
head =
[1, 2, 3, 4]