Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Analyse:similiar to merge sort algorithm. Reuse the code in Merge Sorted Lists.
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: Onelistnode* mergeklists (vector<listnode*>&lists) { A if(lists.size () = =0)returnNULL; - if(lists.size () = =1)returnlists[0]; - the returnDivide (lists,0, Lists.size ()-1); - } -Listnode* Divide (vector<listnode*> &lists,intLeftintRight ) { - if(Left <Right ) { + intM = (left + right)/2; - returnMerge2lists (Divide (lists, left, m), divide (lists, M +1, right)); + } A returnlists[0]; at } -ListNode *merge2lists (ListNode *l1, ListNode *L2) { -ListNode Pre (-1); - - for(listnode* p = ⪯ L1 | | L2; p = p->next) { - intVal1 = L1 = = nullptr? Int_max:l1->Val; in intVal2 = L2 = = nullptr? Int_max:l2->Val; - to if(Val1 >val2) { +P->next =L2; -L2 = l2->Next; the } * Else{ $P->next =L1;Panax NotoginsengL1 = l1->Next; - } the } + returnPre.next; A } the};
Merge K Sorted Lists