Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Multi-way merge.
1. Use the MAKE_HEAP function to maintain a minimum heap of size k.
Note: Because the default is the maximum heap, you need to customize the Compare function, which is defined as static or global.
Because Make_heap is a global function, you cannot call a non-static member function.
2. Remove the smallest element (i.e. lists[0]), and use the POP_HEAP function to move the smallest element to the last
3, Wakahara Lists[0], that is, the current lists[last] There are subsequent nodes, then use PUSH_HEAP to adjust its successor nodes into the heap.
Otherwise the linked list is merged and deleted.
Repeat 2, 3 until all linked lists have been merged.
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: Static BOOLCompConstlistnode* N1,Constlistnode*n2) { returnN1->val > n2->val;//> Builds minimum heap. Default < builds maximum heap} ListNode*mergeklists (Vector<listnode *> &lists) { //Remove NULL listsVector<listnode*>::iterator it =Lists.begin (); while(It! =Lists.end ()) { if(*it = =NULL)//Empty ListNodeLists.erase (IT);//return the iterator to the next element Elseit++; } if(Lists.empty ())//All empty returnNULL; //Make minimum heapmake_heap (Lists.begin (), Lists.end (), comp); ListNode* Newhead =NewListNode (-1); ListNode* Tail =Newhead; while(!Lists.empty ()) {Tail->next = lists[0]; Tail= tail->Next; //Remove the minimum element to the last position, which is lists[last]pop_heap (Lists.begin (), Lists.end (), comp); intLast = Lists.size ()-1; if(Lists[last]->next! =NULL) {//Lists[last] have been inserted into the result, and remove it, retrieve the next elementLists[last] = lists[last]->Next; //Place New Lists[last] to right position of heappush_heap (Lists.begin (), Lists.end (), comp); } Else //Lists[last] is all in result, remove itLists.pop_back (); } returnNewhead->Next; }};
"Leetcode" Merge K Sorted Lists