# . Merge k Sorted Lists

Source: Internet
Author: User

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Subscribe to see which companies asked this question

Idea: Similar to merge sort, each list is already sorted, now only need to merge each linked list into a list. Point: Divide and conquer, and finally merge.

`/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution {Private: ListNode* MERGE_HELP (Vector<listnode*>&lists,intLintR) {        if(l>=R)returnLists[l]; intMid= (L+R)/2; ListNode* left =merge_help (Lists,l,mid); ListNode* RIGHT=MERGE_HELP (lists,mid+1, R); ListNode* Temp =NewListNode (-1); ListNode*cur =temp;  while(left&&Right ) {            if(left->val<=right->val) {cur->next =Left ; Left=left->Next; }            Else{cur->next=Right ; Right=right->Next; } cur=cur->Next; }        if(left) cur->next=Left ; if(right) cur->next=Right ; returnTemp->Next; } Public: ListNode* Mergeklists (vector<listnode*>&lists) {        if(lists.size () = =0)            returnNULL; returnMerge_help (lists,0, Lists.size ()-1); }        };`

. 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.