Problem 24: Swap Nodes in Pairs
Question
LeetCode Link | 24. Swap Nodes in Pairs | Medium
Given 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.)
Constraints
- The number of nodes in the list is in the range
[0, 100]
0 <= Node.val <= 100
Examples
Example 1
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Example 2
Input: head = []
Output: []
Example 3
Input: head = [1]
Output: [1]
Solution Approach
Method: Manual / Simulate
Constrains
- None
This method does not have any limitations.
Concept Explanation
Let’s break this question into a smaller one, how to swap two node?
The answer is simple, just set the secondNode.next
to the firstNode
.
What if there are more than one pairs in the Linked List?
Firstly, we will need to fix the connections between pairs. If we have a list [1, 2, 3, 4]
, after swap it becomes [2, 1, 3, 4]
but 1.next
is still point to 2
. Thus, we need to set 1.next
to 3
which is the third node, and it becomes as follow:
1 | // Swap the nodes in pairs |
What if the pair is not the first pair?
if we handling the second pair [3, 4]
, we will find that the next pointer of the previous pair is also wrong, which means we have to set 1.next
to 4
to meet the complete list [2, 1, 4, 3]
.
This cause the code has two condition:
- If this is the first pair, we don’t need to fix the previous pair’s next pointer.
- Otherwise, fix the connection.
To make logic simple and unify, we could use a dummy node to solve this question. By adding a dummy node before the head node, every pair no longer a first pair.
Finally, return the head node after swaping all pairs by returning dummyNode.next
as we mentioned dummy node is ahead of the head node.
Code
- Time complexity: O(n)
- Space complexity: O(1)
TypeScript
1 | /** |
Conclusion
This question can also be implement using the recursion since this is a unified loop. Remember that the graph is always your friend, if you can not figure out the logic clearly, just draw a graph. Never start to code without a clear logic, or you are gonna messed up your code.