s0021
continuous-integration/drone/push Build is passing Details

This commit is contained in:
Sainnhe Park 2022-11-05 10:02:49 +08:00
parent 955655bb0f
commit 2031712234
2 changed files with 59 additions and 0 deletions

View File

@ -0,0 +1,19 @@
#ifndef S0021_MERGE_TWO_SORTED_LISTS
#define S0021_MERGE_TWO_SORTED_LISTS
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) {}
};
#include <limits>
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2);
};
#endif

View File

@ -0,0 +1,40 @@
#include "s0021_merge_two_sorted_lists.hpp"
ListNode* Solution::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;
}