diff --git a/cpp/more/0021.cpp b/cpp/more/0021.cpp new file mode 100644 index 0000000..2866171 --- /dev/null +++ b/cpp/more/0021.cpp @@ -0,0 +1,48 @@ +#include + +/** + * Definition for singly-linked list. + */ +struct ListNode { + int val; + ListNode* next; + + explicit ListNode(int x = 0, ListNode* next = nullptr) : val(x), next(next) {} +}; + +class Solution { +public: + static ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { + ListNode node; + ListNode* ptr = &node; + while (list1 && list2) { + if (list1->val < list2->val) { + list1 = (ptr->next = list1)->next; + } else { + list2 = (ptr->next = list2) ->next; + } + ptr = ptr->next; + } + ptr->next = list1 ? list1 : list2; + return node.next; + } +}; + +ListNode* construct(int x) { + return new ListNode(x); +} + +template +ListNode* construct(int x, Ts... xs) { + return new ListNode(x, construct(xs...)); +} + +int main() { + ListNode* list1 = construct(1, 2, 4); + ListNode* list2 = construct(1, 3, 4); + ListNode* head = Solution::mergeTwoLists(list1, list2); + for (ListNode* ptr = head; ptr; ptr = ptr->next) { + std::printf("%d ", ptr->val); + } + return 0; +} diff --git a/cpp/more/CMakeLists.txt b/cpp/more/CMakeLists.txt index 1241580..3dd6e05 100644 --- a/cpp/more/CMakeLists.txt +++ b/cpp/more/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(more) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(more 0344.cpp) +ADD_EXECUTABLE(more 0021.cpp)