Idea: Put the head of each list in the smallest heap, take the first heap at a time, and then take the next node out into the heap.
1 classcmp{2 Public:3 BOOL operator() (listnode* l1,listnode*L2)4 {5 returnL1->val>l2->Val;6 }7 };8 classSolution {9 Public:Tenlistnode* mergeklists (vector<listnode*>&lists) { Onelistnode* head,*ptr1,*ptr2; APriority_queue<listnode*,vector<listnode*>,cmp>minheap; - for(intI=0; I<lists.size (); i++) - if(lists[i]!=NULL) the Minheap.push (Lists[i]); - if(Minheap.empty ()) - returnNULL; -Head = PTR1 = ptr2=minheap.top (); + Minheap.pop (); - if(ptr1->next!=NULL) +Minheap.push (ptr1->next); A at while(!minheap.empty ()) - { -PTR1 =minheap.top (); - //cout<<ptr1->val<<endl; -Ptr2->next =ptr1; -PTR2 = ptr2->Next; in Minheap.pop (); - if(ptr1->next==NULL) to Continue; +Minheap.push (ptr1->next); - } the returnhead; * } $};
Merge K Sorted Lists