/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#include<stdlib.h>
struct ListNode*merge(struct ListNode*h1,struct ListNode*h2)
{
struct ListNode*head,*temp,*p=h1,*q=h2;
if(!p) return q;
if(!q) return p;
if(p->val<q->val)
{head=p;temp=p;p=p->next;}
else
{head=q;temp=q;q=q->next;}
while(p&&q)
{
if(p->val<q->val)
{temp->next=p;temp=temp->next;p=p->next;}
else
{temp->next=q;temp=temp->next;q=q->next;}
}
if(!p)//p is empty
{
temp=head;
while(temp->next)
temp=temp->next;
temp->next=q;
}else//q is empty
{
temp=head;
while(temp->next)
temp=temp->next;
temp->next=p;
}
return head;
}
struct ListNode* mergesort(struct ListNode** lists,int low,int high)
{
int mid=(low+high)/2;
struct ListNode *h1,*h2,*h;
if(high==0&&low==0)
return NULL;
if(low==high)
h=lists[low];
else if(high-low==1)
h=merge(lists[low],lists[high]);
else
{
h1=mergesort(lists,low,mid);
h2=mergesort(lists,mid+1,high);
h=merge(h1,h2);
}
return h;
}
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize){
if(listsSize==0)
return NULL;
else if(listsSize==1)
return lists[0];//特殊情况
struct ListNode* head=mergesort(lists,0,listsSize-1);
return head;
}