Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for singly-linked list.
- * 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) {}
- * };
- */
- class Solution {
- public:
- ListNode* mergeKLists(vector<ListNode*>& lists) {
- ListNode *head = nullptr, *curr = nullptr;
- using Node = pair<int, ListNode*>;
- priority_queue<Node, vector<Node>, greater<Node>> heap;
- for (ListNode *node: lists) {
- if (node != nullptr) {
- heap.emplace(node->val, node);
- }
- }
- while (!heap.empty()) {
- ListNode *top = heap.top().second;
- heap.pop();
- if (head == nullptr) {
- head = curr = top;
- } else {
- curr->next = top;
- curr = top;
- }
- if (top->next != nullptr) {
- heap.emplace(top->next->val, top->next);
- }
- top->next = nullptr;
- }
- return head;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement