Leetcode-merge K sorted lists

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.