Skip to content

Instantly share code, notes, and snippets.

@zhangxiaomu01
Created November 10, 2018 05:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhangxiaomu01/ee8a67683b0ea0873b3385ae5814e9be to your computer and use it in GitHub Desktop.
Save zhangxiaomu01/ee8a67683b0ea0873b3385ae5814e9be to your computer and use it in GitHub Desktop.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2){
ListNode head(0);
ListNode* h = &head;
while(l1&&l2){
if(l1->val < l2->val){
h->next = l1;
h=h->next;
l1= l1->next;
}
else{
h->next = l2;
h = h->next;
l2=l2->next;
}
}
if(l1)
{
h->next = l1;
}
if(l2)
{
h->next = l2;
}
return head.next;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
int len_l = lists.size();
if(len_l == 0)
return nullptr;
int step = 1;
while(step < len_l){
for(int i = 0; i + step < len_l; i = i + step*2)
{
lists[i] = mergeTwoLists(lists[i], lists[i+step]);
}
step = step*2;
}
return lists[0];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment