simple c++ solution using priority queue


  • 0
    R
        if(l1->val>l2->val) return 1;
        else
            return 0;
    } 
    class Solution {
    public:
        ListNode* mergeKLists(vector<ListNode*>& lists) {
            //auto comp1=[](ListNode*l1,ListNode*l2)->bool{return(l1->val>l2->val);};
       
            priority_queue<ListNode*,vector<ListNode*>,bool(*)(ListNode*,ListNode*)> pq(comp);
            ListNode*temp=NULL;
            ListNode*start=NULL;
            if(lists.size()==0) return start;
            if(lists.size()==1) return lists[0];
            for(int i=0;i<lists.size();++i){
                if(lists[i])
                    pq.push(lists[i]);
            }
            while(!pq.empty()){
                ListNode*temp2=pq.top();
                pq.pop();
                if(temp2->next) pq.push(temp2->next);
                if(start==NULL){
                    start=temp2;
                    temp=temp2;
                }
                else{
                    temp->next=temp2;
                    temp=temp2;
                }
            }
            return start;
        }
    };``````

Log in to reply
 

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