Merge K sorted lists
Merge K sorted linked lists and return it as one sorted list. analyze and describe its complexity. idea: Put these K linked lists into Multiset. Each time you extract the smallest linked list from Multiset, insert the first node into the result linked list, and then insert the remaining non-empty sublinked list to Multiset.
/*** Definition for singly-linked list. * struct listnode {* int val; * listnode * Next; * listnode (int x): Val (x), next (null ){}*}; */class solution {public: struct CMP // pay attention to the comparison Function Format. Set's comparison function either reloads operator <or writes it into the function call FORM {bool operator () (listnode * const L1, listnode * const l2) const // note the parameter format {If (! L1) return false; If (! L2) return true; return L1-> Val <L2-> Val ;}}; listnode * mergeklists (vector <listnode *> & lists) {int length = lists. size (), I; If (length <= 0) return NULL; Multiset <listnode *, CMP> S; // insert for (I = 0; I <length; I ++) {If (lists [I]) s. insert (lists [I]); // retrieve the null linked list} listnode * head = NULL, * tail = NULL; while (! S. empty () {Multiset <listnode *, CMP >:: iterator iter = S. begin (); listnode * P = * ITER; S. erase (ITER); // P cannot be deleted, because it will delete all linked lists with the same header knot and P if (! Head) {head = P; tail = head;} else {tail-> next = P; tail = P;} p = p-> next; If (p) s. insert (p) ;}if (head) tail-> next = NULL; return head ;}};
Leetcode-merge K sorted lists