From 2031712234f10975e9822f3b42903651160a99cc Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Sat, 5 Nov 2022 10:02:49 +0800 Subject: [PATCH] s0021 --- include/s0021_merge_two_sorted_lists.hpp | 19 +++++++++++ src/s0021_merge_two_sorted_lists.cpp | 40 ++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 include/s0021_merge_two_sorted_lists.hpp create mode 100644 src/s0021_merge_two_sorted_lists.cpp diff --git a/include/s0021_merge_two_sorted_lists.hpp b/include/s0021_merge_two_sorted_lists.hpp new file mode 100644 index 0000000..152ca8b --- /dev/null +++ b/include/s0021_merge_two_sorted_lists.hpp @@ -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 + +class Solution { + public: + ListNode* mergeTwoLists(ListNode* list1, ListNode* list2); +}; + +#endif diff --git a/src/s0021_merge_two_sorted_lists.cpp b/src/s0021_merge_two_sorted_lists.cpp new file mode 100644 index 0000000..73b83bd --- /dev/null +++ b/src/s0021_merge_two_sorted_lists.cpp @@ -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::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; +}