Merge Two Sorted Lists
LeetCode #21 · Easy · Linked Lists · C++ solution with worked-out approach and complexity analysis.
Approach
Iterative
Create a new head for the result list. Iterate through both lists, comparing values and appending the smaller value to the result list. If one list becomes empty, append the rest of the other list.
Time
O(n + m)
Space
O(1)
(ignoring the new nodes created in this specific implementation)
Problem description(from LeetCode)
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]
Constraints
- •The number of nodes in both lists is in the range [0, 50].
- •-100 <= Node.val <= 100
- •Both list1 and list2 are sorted in non-decreasing order.
C++ Solution
solution.cpp
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) {
if (list1 == nullptr) return list2;
if (list2 == nullptr) return list1;
ListNode *head;
if (list1->val <= list2->val) {
head = new ListNode(list1->val);
list1 = list1->next;
} else {
head = new ListNode(list2->val);
list2 = list2->next;
}
ListNode *tail = head;
while (list1 != nullptr || list2 != nullptr) {
if (list1 == nullptr) {
tail->next = list2;
break;
}
if (list2 == nullptr) {
tail->next = list1;
break;
}
if (list1->val <= list2->val) {
tail->next = new ListNode(list1->val);
tail = tail->next;
list1 = list1->next;
} else {
tail->next = new ListNode(list2->val);
tail = tail->next;
list2 = list2->next;
}
}
return head;
}
};