Swap Nodes in Pairs
Medium
Given the head of a singly linked list, swap every two adjacent nodes in the linked list.
You must swap the nodes themselves, not just their values.
Return the head of the modified linked list.
Example 1
Input
n = 4 head = [1, 2, 3, 4]
Output
[2, 1, 4, 3]
Explanation
The first pair [1, 2] becomes [2, 1].
The second pair [3, 4] becomes [4, 3].
Therefore, the resulting list is [2, 1, 4, 3].
Example 2
Input
n = 3 head = [1, 2, 3]
Output
[2, 1, 3]
Explanation
The first two nodes are swapped.
The last node has no pair, so it remains unchanged.
Constraints
0 <= n <= 100
0 <= Node.val <= 100
Nodes must be swapped by changing links.
Do not swap only the values.
Hints:
Hint 1
Consider the linked list as pairs:
1 → 2 → 3 → 4
Swap the first two nodes, then recursively or iteratively process the remaining list.
Hint 2
For every pair:
first → second → remaining
Change the links so that:
second → first → remaining
Auto
Loading editor...
Input
Expected Output