diff --git a/2202/220205.cpp b/2202/220205.cpp new file mode 100644 index 0000000..71b778a --- /dev/null +++ b/2202/220205.cpp @@ -0,0 +1,63 @@ +#include +#include + +/** + * Definition for singly-linked list. + */ +struct ListNode { + int val; + ListNode* next; + explicit ListNode(int x = 0, ListNode* next = nullptr) : val(x), next(next) {} + ~ListNode() { delete this->next; } +}; + +struct NodeCompare { + bool operator()(const ListNode* const x, const ListNode* const y) const { + return x->val > y->val; + } +}; + +class Solution { +public: + static ListNode* mergeKLists(const std::vector& lists) { + std::priority_queue, NodeCompare> q; + for (ListNode* const& ptr : lists) { + if (ptr) + q.push(ptr); + } + if (q.empty()) + return nullptr; + ListNode* const head = q.top(); + ListNode* tail = head; + if (head->next) + q.push(head->next); + q.pop(); + while (!q.empty()) { + ListNode* const t = q.top(); + q.pop(); + if (t->next) + q.push(t->next); + tail->next = t; + tail = t; + } + return head; + } +}; + +ListNode* construct(int x) { + return new ListNode(x); +} + +template +ListNode* construct(int x, Ts... xs) { + return new ListNode(x, construct(xs...)); +} + +int main() { + std::vector args {construct(1, 4, 5), construct(1, 3, 4), construct(2, 6)}; + ListNode* ret = Solution::mergeKLists(args); + for (ListNode* ptr = ret; ptr; ptr = ptr->next) { + std::cout << ptr->val << ' '; + } + return 0; +} diff --git a/2202/CMakeLists.txt b/2202/CMakeLists.txt index e96caac..90d22c9 100644 --- a/2202/CMakeLists.txt +++ b/2202/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2202) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2202 220205-CN.cpp) +ADD_EXECUTABLE(2202 220205.cpp)