This commit is contained in:
parent
955655bb0f
commit
2031712234
19
include/s0021_merge_two_sorted_lists.hpp
Normal file
19
include/s0021_merge_two_sorted_lists.hpp
Normal 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
|
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;
|
||||
}
|
Loading…
Reference in New Issue
Block a user