Today, I solved "Remove Nth Node From End of List."
Description:
In this problem, we are gonna delete nth node from the end of the list. For example of case 1, we found the "4" is the 2nd node from the end of the list.
But how can we delete and how can we know nth node from the end?
Solution:
1. First, we are gonna make two pointers on the list: left and right.
2. "right" is "n" ahead of left. For example, we are gonna find the nth from the end, then right is 2 list ahead of the left.
3. However, if we move right and left at the end of list, left points the 4 node(2th node from the end of the list).
So, we have to find how we connect 3 -> 5 (in case 1).
For solution, I made the dummy node which points "0". Now the list is like: [0, 1, 2, 3, 4, 5]
"left" points to the 0(dummy), and move right nth ahead of the dummy!
[0(left), 1, 2[right], 3, 4, 5].
We are gonna move those two pointers until right points to null.
Then the list is like [0, 1, 2, 3(left), 4, 5(right)]
Now, we connect 3 to 5, and 4 is deleted!
Don't forget return dummy.next, because dummy points to 0 which we made virtually at the first.
'LeetCode ๐๏ธ > Linked List' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
23. Merge k Sorted Lists (0) | 2023.05.01 |
---|---|
141. Linked List Cycle (0) | 2023.05.01 |
143. Reorder List (0) | 2023.04.25 |
21. Merge Two Sorted Lists (0) | 2023.04.10 |
206. Reverse Linked List (0) | 2023.04.09 |