140. Swap Nodes in Pairs
Medium · Linked List
Given a linked list, swap every two adjacent nodes and return the head of the modified list. You must solve the problem without modifying the values in the list's nodes (only nodes themselves may be changed).
For example, if the input is 1→2→3→4, the output should be 2→1→4→3. If the input is 1→2→3, the output should be 2→1→3 (the last node stays in place since it has no pair).
Examples
Example 1 Input: [1, 2, 3, 4] Output: [2, 1, 4, 3] Explanation: Swap nodes 1 and 2, then swap nodes 3 and 4. The list becomes 2→1→4→3.
Example 2 Input: [1, 2, 3] Output: [2, 1, 3] Explanation: Swap nodes 1 and 2. Node 3 has no pair, so it remains in place. The list becomes 2→1→3.
Constraints
- Standard input/output constraints apply