This commit is contained in:
40
src/s0021_merge_two_sorted_lists.cpp
Normal file
40
src/s0021_merge_two_sorted_lists.cpp
Normal 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;
|
||||
}
|
Reference in New Issue
Block a user