Swap Nodes in Pairs - Problem
Swap Adjacent Node Pairs in a Linked List
Imagine you have a chain of connected nodes, and you need to swap every two adjacent nodes while keeping the chain intact. Given the head of a linked list, your task is to swap every two adjacent nodes and return the new head of the modified list.
Key Rules:
Example:
Imagine you have a chain of connected nodes, and you need to swap every two adjacent nodes while keeping the chain intact. Given the head of a linked list, your task is to swap every two adjacent nodes and return the new head of the modified list.
Key Rules:
- You can only change the node connections - not the values inside the nodes
- If there's an odd number of nodes, the last node remains in its original position
- The solution should work in-place without creating new nodes
Example:
1→2→3→4 becomes 2→1→4→3 Input & Output
example_1.py — Basic Even Length List
$
Input:
head = [1,2,3,4]
›
Output:
[2,1,4,3]
💡 Note:
The first pair (1,2) swaps to (2,1), and the second pair (3,4) swaps to (4,3). Result: 2→1→4→3
example_2.py — Odd Length List
$
Input:
head = [1,2,3]
›
Output:
[2,1,3]
💡 Note:
The first pair (1,2) swaps to (2,1), but node 3 has no pair so it remains in place. Result: 2→1→3
example_3.py — Edge Cases
$
Input:
head = [] OR head = [1]
›
Output:
[] OR [1]
💡 Note:
Empty list returns empty. Single node has no pair to swap with, so it remains unchanged.
Constraints
- The number of nodes in the list is in the range [0, 100]
- 0 ≤ Node.val ≤ 100
- You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed)
Visualization
Tap to expand
Understanding the Visualization
1
Setup Stage
Place a director (dummy node) at the front to coordinate the swaps
2
Identify Partners
Point to the next two dancers who need to swap positions
3
Coordinate Swap
Carefully rewire connections so partners swap without breaking the line
4
Move to Next Pair
Director moves to supervise the next pair of dancers
Key Takeaway
🎯 Key Insight: Use a dummy node as an anchor and maintain careful pointer tracking to swap pairs efficiently without losing connections in the linked list.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code