直接合并
/**
* 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) {
const int inf=2147483647;
int j,len,m,k;
m=sizeof(int);
len=lists.size();
ListNode* anshead=new ListNode(0);
ListNode* p=anshead;
while(1){
m=inf;
for(j=0;j<len;j++){
if(lists[j]==NULL){
lists[j]=new ListNode(inf);
}
if(lists[j]->val<m){
m=lists[j]->val;
k=j;
}
}
if(m<inf){;
p->next=new ListNode(lists[k]->val);
p=p->next;
lists[k]=lists[k]->next;
}
else{
break;
}
}
return anshead->next;
}
};
分治法(两两合并)
/**
* 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) {
if(l1==NULL){
return l2;
}
else if(l2==NULL){
return l1;
}
else if(l1->val>l2->val){
l2->next=mergeTwoLists(l1,l2->next);
return l2;
}
else{
l1->next=mergeTwoLists(l1->next,l2);
return l1;
}
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode *p1=new ListNode(0);
ListNode *p2=new ListNode(0);
if(lists.size()==0){
return NULL;
}
queue<ListNode*> dui;
for(int i=0;i<lists.size();i++){
dui.push(lists[i]);
}
while(dui.size()>1){
p1=dui.front();
dui.pop();
p2=dui.front();
dui.pop();
dui.push(mergeTwoLists(p1,p2));
}
return dui.front();
}
};