Junior — Middle+
Swapping adjacent nodes in a singly linked list
livecode
Task condition
Given a singly linked list listHead. It is required to swap every adjacent pair of nodes, forming pairs, and return a pointer to the new first element. If the number of nodes is odd, the last element remains in place.
Example 1: Input: listHead = [1,2,3,4] Output: [2,1,4,3] Explanation:
- The pair (1,2) is swapped → (2,1).
- The pair (3,4) is swapped → (4,3).
- Final list: [2,1,4,3].
Example 2: Input: listHead = [1,2,3] Output: [2,1,3] Explanation:
- The pair (1,2) is swapped → (2,1).
- The remaining single node (3) remains unchanged.
- Final list: [2,1,3].
Example 3: Input: listHead = [] Output: [] Explanation: An empty list remains empty as there are no nodes to swap.