[LeetCode][1721. Swapping Nodes in a Linked List] 3 Approaches: Swapping Values and Swapping Nodes with Image Explanation
By Long Luo
This article is the solution 3 Approaches: Swapping Values and Swapping Nodes with Image Explanation of Problem 1721. Swapping Nodes in a Linked List.
Here shows 3 Approaches to slove this problem: ArrayList and Two Pointers.
Intuition
Since the only contain values, we can just just swap the values of two nodes. It’s very easy. All we need to do is to find these two nodes and swap their values.
If we swap nodes, it will be more difficult than swap values.
ArrayList(Swapping Values)
We can use an to record all the nodes of the linked list. We can just swap the values of two nodes.
1 | // BF List time: O(n) space: O(n) |
Analysis
- Time Complexity:
- Space Complexity:
Two Pointers(Swapping Values)
The space complexity of Method is . We can use Two Pointers to make it to .
Just follow the bellow steps:
- Find the node from the front which is left.
- Make left node as the current node, right node from the front, when the current node reach end, right node is just the last element.
- Swap their values.
1 | // Two Pointers time: O(n) space: O(1) |
Analysis
- Time Complexity:
- Space Complexity:
Two Pointers(Swapping Nodes)
In fact, Swapping Nodes will be more difficult. There are some corner cases.
We need to store both the previous and current nodes of these two nodes, denoted them as and .
However, here are 3 corner cases, as the bellow image shows.
We must handle these 3 cases.
1 | // Two Pointers Swap Nodes time: O(n) space: O(1) |
Analysis
- Time Complexity:
- Space Complexity:
All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:-)
Explore More Leetcode Solutions. 😉😃💗