3.1 KiB
3.1 KiB
Leetcode Merge-Two-Sorted-Lists
2022-06-14 22:57
Algorithms:
#algorithm #two_pointers #recursion
Data structures:
#DS #linked_list
Difficulty:
#leetcode #coding_problem #difficulty_easy
Related topics:
Links:
Problem
You are given the heads of two sorted linked lists list1
and list2
.
Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Examples
Example 1:
**Input:** list1 = [1,2,4], list2 = [1,3,4]
**Output:** [1,1,2,3,4,4]
Example 2:
**Input:** list1 = [], list2 = []
**Output:** []
Example 3:
**Input:** list1 = [], list2 = [0]
**Output:** [0]
Constraints
- The number of nodes in both lists is in the range
[0, 50]
. -100 <= Node.val <= 100
- Both
list1
andlist2
are sorted in non-decreasing order.
Thoughts
Two pointers method
This is a #two_pointers algorithm, I've done similar problems at leetcode's array list. The only thing to watch out for is when there is one list remaining, remember to add the tails.
Recursion
Very simple for recursion
Base Case:
- Both are nullptr -> return nullptr
- One is nullptr -> return another
Pseudocode:
- Check for base case:
- if list1->val > list2->val, list2's next should be the merged result
- if list2->val > list1->val, list1's next should be the merged result.
Solution
Recursion
class Solution {
public:
ListNode *mergeTwoLists(ListNode *list1, ListNode *list2) {
// Recursion
// Base case, one is empty or both empty
if (!list1) {
return list2;
} else if (!list2) {
return list1;
}
if (list1->val > list2->val) {
// insert list1 after list2
list2->next = mergeTwoLists(list1, list2->next);
return list2;
} else {
list1->next = mergeTwoLists(list1->next, list2);
return list1;
}
}
};
Two pointers
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode *mergeTwoLists(ListNode *list1, ListNode *list2) {
// 2 Pointers, Space and time O(m + n);
ListNode *ptr1 = list1;
ListNode *ptr2 = list2;
ListNode *dummyHead = new ListNode();
ListNode *ptr3 = dummyHead;
while (ptr2 != NULL && ptr1 != NULL) {
if (ptr2->val <= ptr1->val) {
ptr3->next = ptr2;
ptr2 = ptr2->next;
} else {
ptr3->next = ptr1;
ptr1 = ptr1->next;
}
ptr3 = ptr3->next;
}
if (ptr2 == NULL) {
ptr3->next = ptr1;
} else if (ptr1 == NULL) {
ptr3->next = ptr2;
}
return dummyHead->next;
}
};