Today, I solved the Merge Two Sorted Lists.
Description:
We have two lists, and we are gonna merge those two lists. The point is that we are gonna sort new list in non-decreasing order.
Solution1:
We make dummy node to avoid some error. And, we make curr node to know our location in both lists.
Our while loop runs until we put every values in list1 and list2.
If the value of list1 is less than list2, then curr points to list1.next
else the value of list2 is less than list1, then curr points to list2.next
And then we move the curr to the location of curr.next
Now, our node looks like this:
[output] --> [dummy] --> [first value] --> [second value] ...
However, if list1 and list2 have different length, there should be remaining node in list1 or list2.
Before returning our output, we should make sure put every node to our output list.
Solution(Recursion Method):
The algorithms is similar to the iteractive method.
To avoid remaining elements in both lists, we put if not list1 or not list2: return list1 or list2
Now, if the value of list1 is less than list2, we move to the next value of list1 with recursion method.
Otherwise, we move to the next value of list2.
'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 |
19. Remove Nth Node From End of List (1) | 2023.04.23 |
206. Reverse Linked List (0) | 2023.04.09 |