C++ short&easy solution using minheap

  • 3
    class Solution {
        ListNode* mergeKLists(vector<ListNode*>& lists) {
            if (lists.empty()) return nullptr;
            ListNode* pseudoHead = new ListNode(0);
            auto comp = [](ListNode* n1, ListNode* n2) { return n1->val > n2->val; };
            priority_queue<ListNode*, vector<ListNode*>, decltype(comp)> que{comp};
            for (ListNode* node: lists)
                if (node) que.push(node);
            ListNode* node = pseudoHead;
            while (que.size())
                ListNode* next = que.top();
                if (next->next) que.push(next->next);
                node->next = next;
                node = node->next;
            return pseudoHead->next;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.