Leetcode-merge k Sorted Lists

Source: Internet
Author: User

https://leetcode.com/problems/merge-k-sorted-lists/

Topic Analysis:

Method 1:

By dividing the method, the K-linked list is divided into two parts, respectively, to merge the two parts, until the last only two, you can use the merge function to merge two linked lists

Time complexity Analysis: (to be written)

The code is as follows:

`classSolution { Public: ListNode* Mergeklists (vector<listnode*>&lists) {        if(Lists.empty ()) {returnNULL; }        returnMergelist (lists,0, Lists.size ()-1); }Private: ListNode* Mergelist (vector<listnode*> &lists,intLintr) {if(L <r) {intm = (L + r)/2; ListNode*L1 =mergelist (lists, L, M); ListNode*L2 = mergelist (lists, m+1, R); returnmergelist (L1, L2); }        Else        {            returnLists[l]; }} ListNode*mergelist (ListNode *l1, ListNode *L2) {ListNode Dummy (-1); ListNode*P1 =L1; ListNode*P2 =L2; ListNode*p = &dummy;  while(P1! = NULL && P2! =NULL) {            if(P1->val < p2->val) {P->next =P1; P1= p1->Next; }            Else{p->next =P2; P2= p2->Next; } P= p->Next; }        if(P1! =NULL) {P->next =P1; }        if(P2! =NULL) {P->next =P2; }        returnDummy.next; }};`

Method 2:

Using heaps to implement (in writing)

Leetcode-merge k Sorted Lists

Related Keywords:

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.