https://leetcode.com/problems/merge-k-sorted-lists/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* head=new ListNode(0);
ListNode* temp=head; //标记用的
while (l1&&l2) {
if(l1->val < l2->val){
head->next=l1;
l1=l1->next;
head=head->next;
}
else{
head->next=l2;
l2=l2->next;
head=head->next;
}
}
if(l1){
head->next=l1;
}
else{
head->next=l2;
}
return temp->next;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
int n = lists.size();
if(n==0) return NULL;
while (n>1) {
int k = (n+1)/2;
for(int i=0;i<n/2;i++){
lists[i] = mergeTwoLists(lists[i], lists[i+k]);
}
n=k; //一次归并后,缩小范围
}
return lists[0];
}
};