MergeKSorted linked lists and return it as one sorted list. analyze and describe its complexity.
Combine K ordered linked lists into an ordered linked list.
Thought, we have previously done the merge operation of two ordered linked lists. For K linked lists, we first thought about whether it can be converted into the merge of two familiar linked lists, we can first divide K linked lists into two parts. First, we can merge these two parts in order and then combine the two linked lists. This is a recursive description, it is easy to implement this program using recursion, andThe sort of arrays is similar..
Accepted solution:
/*** Definition for singly-linked list. * struct listnode {* int val; * listnode * Next; * listnode (int x): Val (x), next (null ){}*}; */class solution {public: listnode * mergeklists (vector <listnode *> & lists) {return mergesort (lists, 0, lists. size ()-1);} listnode * mergesort (vector <listnode *> & lists, int begin, int end) {If (begin> end) return NULL; if (begin = END) return lists [begin]; int mid = (beg In + end)/2; listnode * head1 = mergesort (lists, begin, mid); listnode * head2 = mergesort (lists, Mid + 1, end ); listnode * dummyhead = new listnode (0), * P = dummyhead; while (head1! = NULL & head2! = NULL) {If (head1-> Val