41 lines
1.0 KiB
C++
41 lines
1.0 KiB
C++
#include "s0021_merge_two_sorted_lists.hpp"
|
|
|
|
ListNode* S0021::mergeTwoLists(ListNode* list1, ListNode* list2) {
|
|
if (list1 == nullptr) {
|
|
return list2;
|
|
} else if (list2 == nullptr) {
|
|
return list1;
|
|
}
|
|
ListNode dummy = ListNode(-std::numeric_limits<int>::max());
|
|
if (list1->val > list2->val) {
|
|
dummy.next = list2;
|
|
list2 = list2->next;
|
|
} else {
|
|
dummy.next = list1;
|
|
list1 = list1->next;
|
|
}
|
|
ListNode* current = dummy.next;
|
|
while (!(list1 == nullptr && list2 == nullptr)) {
|
|
if (list1 == nullptr) {
|
|
current->next = list2;
|
|
current = current->next;
|
|
list2 = list2->next;
|
|
} else if (list2 == nullptr) {
|
|
current->next = list1;
|
|
current = current->next;
|
|
list1 = list1->next;
|
|
} else {
|
|
if (list1->val > list2->val) {
|
|
current->next = list2;
|
|
current = current->next;
|
|
list2 = list2->next;
|
|
} else {
|
|
current->next = list1;
|
|
current = current->next;
|
|
list1 = list1->next;
|
|
}
|
|
}
|
|
}
|
|
return dummy.next;
|
|
}
|