Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Merges K ordered linked lists.
The idea of this problem is similar to merge sort, and merge sort has two kinds of thinking, one is recursive from the top down, one is from the bottom to the upper iteration, here choose the latter, each iteration merges the adjacent two linked list, and finally returns the list when the number of the list is 1 o'clock. Time complexity is O (N*LOGK), n is the average length of the linked list, the code is as follows:
listnode* Merge2 (listnode* L1, listnode*L2); ListNode* Mergeklists (vector<listnode*>&lists) { intn =lists.size (); if(0==N)returnNULL; for(intlen=1; len<n; len*=2) { for(intI=0; i+len<n; i+=len*2) Lists[i]= Merge2 (Lists[i], lists[i+Len]); } returnlists[0];} ListNode* Merge2 (listnode* L1, listnode*L2) {ListNode Fake_head (0); ListNode* p = &Fake_head; while(L1!=null && l2!=NULL) { if(L1->val <= l2->val) {P->next =L1; P= p->Next; L1= l1->Next; } Else{p->next =L2; P= p->Next; L2= l2->Next; }} P->next = (l1!=null)?L1:l2; returnFake_head.next;}
. Merge k Sorted Lists