Leetcode 21. Merge Two Sorted Lists
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.
Input:
list1: 1 -> 2 -> 4
list2: 1 -> 3 -> 4
Output:
1 -> 1 -> 2 -> 3 -> 4 -> 4
list1
and list2
:
// 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) {
// Create a dummy node to provide easy manipulation of new list
ListNode dummy;
ListNode* tail = &dummy;
// Traverse both lists
while (list1 != nullptr && list2 != nullptr) {
if (list1->val < list2->val) {
tail->next = list1;
list1 = list1->next;
} else {
tail->next = list2;
list2 = list2->next;
}
tail = tail->next;
}
// Attach the remaining nodes, if any
if (list1 != nullptr) {
tail->next = list1;
} else {
tail->next = list2;
}
// Return the head of the merged list
return dummy.next;
}
};
n
is the number of nodes in list1
and m
is the number of nodes in list2
. This is because we traverse each list exactly once.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?