My simple c++ solution using heap


  • 2
    K
    class compare{
    public:
    bool operator()(const ListNode* a, const ListNode* b)
    {
        return a->val > b->val;
    }
    };
    class Solution {
    public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        priority_queue<ListNode *, vector<ListNode*>, compare>heap;
        ListNode * newhead= new ListNode(0);
        ListNode * cur=newhead;
        for(auto & node : lists){
            if(node)heap.push(node);
        }
        while(!heap.empty()){
            ListNode * temp=heap.top();
            heap.pop();
            cur->next=temp;
            if(temp->next)heap.push(temp->next);
            cur=cur->next;
        }
        
        return newhead->next;
    }
    };

Log in to reply
 

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