Algorithm-Day31-Swap-Nodes-in-Pairs-lc-24
π§© Problem Description
Given the head
of a linked list, swap every two adjacent nodes and return its head.
You must solve the problem without modifying the values in the listβs nodes (i.e., only nodes themselves may be changed.)
π¬ Example
1 | Input: head = [1,2,3,4] |
π‘ Intuition
This is a classic linked list node manipulation problem.
- Use a dummy node to simplify edge cases.
- Iterate through the list in pairs.
- For each pair:
- Update pointers to swap the two nodes.
- Move to the next pair.
π’ Java Code (Iterative)
1 | class Solution { |
π Java Code (Recursive)
1 | class Solution { |
β± Time and Space Complexity
- Time Complexity: O(n), where n is the number of nodes
- Space Complexity:
- Iterative: O(1)
- Recursive: O(n) due to recursion stack
βοΈ Summary
- Good test of pointer manipulation in linked lists.
- Practice both iterative and recursive approaches.
- Understanding node-level swaps is essential for problems like:
lc-25
: Reverse Nodes in k-Grouplc-92
: Reverse Linked List II
Dummy nodes make linked list problems so much easier β use them!