A C++ solution with priority_queue


  • 0
    R
    class Solution {
    private:
    struct cmp{
        bool operator()(ListNode const *a, ListNode const *b){
            return a->val > b->val;
        }
    };
    
    public:
        ListNode* mergeKLists(vector<ListNode*>& lists) {
            ListNode *head = new ListNode(0);
            ListNode *now(head);
            priority_queue<ListNode*, vector<ListNode*>, cmp>Q;
            for(int i = 0; i < lists.size(); i++)
                if(lists[i])
                    Q.push(lists[i]);
            while(!Q.empty()){
                ListNode *top = Q.top();
                Q.pop();
                now->next = new ListNode(0);
                now->next->val = top->val;
                now = now->next;
                if(top->next)
                    Q.push(top->next);
            }
            return head->next;
        }
    };
    
    

Log in to reply
 

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