2.4 KiB
2.4 KiB
Leetcode Merge-Two-Sorted-Lists
2022-06-14 22:57
Algorithms:
#algorithm #two_pointers
Data structures:
#DS #linked_list
Difficulty:
#leetcode #coding_problem #difficulty-easy
Related topics:
tag:#two_pointers
- Leetcode Intersection-of-Two-Arrays-II
- Leetcode Merge-Sorted-Array
- Leetcode Squares-of-a-Sorted-Array
- Two pointers approach
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
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.
Solution
/**
* 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;
}
};