Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *merge2List(ListNode *h1, ListNode *h2) {
ListNode dummy(-1);
ListNode *tail = &dummy;
while( h1 && h2) {
if(h1->val > h2->val) {
tail->next = h2;
h2 = h2->next;
} else {
tail->next =h1;
h1 = h1->next;
}
tail = tail->next;
}
if(h1) tail->next = h1;
if(h2) tail->next = h2;
return dummy.next;
}
ListNode *sort(int start, int len, vector<ListNode*> &lists) {
if(!len) return nullptr;
if(len == 1) return lists[start];
ListNode *h1 = sort(start, len/2,lists);
ListNode *h2 = sort(start+len/2, len -len/2,lists);
return merge2List(h1,h2);
}
ListNode *mergeKLists(vector<ListNode *> &lists) {
return sort(0, lists.size(),lists);
}
};