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 *mergeKLists(vector<ListNode *> &lists) {
int n = lists.size();
if (n==0) {
return NULL;
}
vector<ListNode *> cur;
vector<ListNode *> res(lists);
while (res.size()>1) {
n = res.size()/2;
for (int i = 0; i < n; i++) {
cur.push_back(mergeTwoLists(res[2*i], res[2*i+1]));
}
if (res.size()%2) {
cur.push_back(res[2*n]);
}
res = cur;
cur.clear();
}
return res[0];
}
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode *head = new ListNode(-1);
ListNode *dummy = head;
if (!l1) {
return l2;
} else if (!l2) {
return l1;
} else {
while (l1 != NULL && l2 != NULL) {
if (l1->val < l2->val) {
head->next = l1;
head = head->next;
l1 = l1->next;
} else {
head->next = l2;
head = head->next;
l2 = l2->next;
}
}
if (l1 == NULL) {
head->next = l2;
} else {
head->next = l1;
}
}
return dummy->next;
}
};