Using priority_queue c++


  • 0
    P
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    
    class Solution {
        class gt{
        public:
            bool operator ()(ListNode* v1, ListNode* v2) const{
                return v1->val > v2->val;
                }
        };
    public:
        ListNode* mergeKLists(vector<ListNode*>& lists) {
            ListNode ans(0);
            priority_queue<ListNode*, vector<ListNode*>, gt> que;
            for(auto p:lists) if(p) que.push(p);
            auto p = &ans;
            while(!que.empty()){
                p->next = que.top();
                p = p->next;
                que.pop();
                if(p->next) que.push(p->next);
            }
            return ans.next;
        }
    };
    

Log in to reply
 

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