add: 220205

This commit is contained in:
Lam Haoyin 2022-02-05 23:36:26 +08:00
parent fc704be306
commit 078e3a226c
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 64 additions and 1 deletions

63
2202/220205.cpp Normal file
View File

@ -0,0 +1,63 @@
#include <queue>
#include <iostream>
/**
* 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<ListNode*>& lists) {
std::priority_queue<ListNode*, std::vector<ListNode*>, 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<typename... Ts>
ListNode* construct(int x, Ts... xs) {
return new ListNode(x, construct(xs...));
}
int main() {
std::vector<ListNode*> 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;
}

View File

@ -3,4 +3,4 @@ PROJECT(2202)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2202 220205-CN.cpp)
ADD_EXECUTABLE(2202 220205.cpp)