add: 0021 [cpp]

This commit is contained in:
Lam Haoyin 2022-02-22 00:11:43 +08:00
parent d7bb6d819c
commit 23639b3e1d
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 49 additions and 1 deletions

48
cpp/more/0021.cpp Normal file
View File

@ -0,0 +1,48 @@
#include <cstdio>
/**
* 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<typename... Ts>
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;
}

View File

@ -3,4 +3,4 @@ PROJECT(more)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(more 0344.cpp)
ADD_EXECUTABLE(more 0021.cpp)