合并 k 个升序的链表并将结果作为一个升序的链表返回其头节点。
方法一:
struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 ) {
//改变原两个链表的指针指向排成新链表 节省空间
struct ListNode* H=malloc(sizeof(struct ListNode));
struct ListNode* cur=H;
while(pHead1!=NULL&&pHead2!=NULL)
{
if(pHead1->val<=pHead2->val)
{
cur->next=pHead1;
cur=cur->next;
pHead1=pHead1->next;
}
else
{
cur->next=pHead2;
cur=cur->next;
pHead2=pHead2->next;
}
}
//若是有一边链表未遍历完,可直接指向当前节点,原链表已排好序
if(pHead1!=NULL)
{
cur->next=pHead1;
}
if(pHead2!=NULL)
{
cur->next=pHead2;
}
return H->next;
// write code here
}
struct ListNode* mergeKLists(struct ListNode** lists, int listsLen ) {
if(listsLen==0)
return NULL;
int i=0;
while(1)
{
for(i=0;i<listsLen/2;i++)//将链表首尾互排直至中间
{
lists[i]=Merge(lists[i],lists[listsLen-i-1]);//排序链表迭代
}
if(listsLen==2)
break;
listsLen=listsLen%2==1?listsLen/2+1:listsLen/2;//对K为单双数的处理
}
return lists[0];
}
方法二:
struct ListNode* sort(struct ListNode* L_phead,struct ListNode* R_phead)
{
struct ListNode* head=malloc(sizeof(struct ListNode));
struct ListNode* cur = head;
while(L_phead!=NULL && R_phead!=NULL)
{
if(L_phead->val < R_phead->val)
{
cur->next=L_phead;
cur=cur->next;
L_phead=L_phead->next;
}
else
{
cur->next=R_phead;
cur=cur->next;
R_phead=R_phead->next;
}
}
if(L_phead!=NULL)
{
cur->next=L_phead;
}
if(R_phead!=NULL)
{
cur->next=R_phead;
}
return head->next;
}
//left:链表的第一个元素下标
//right:链表最后一个元素的下标;
struct ListNode* cut_list(struct ListNode** list,int left,int right)
{
struct ListNode* L_phead;
struct ListNode* R_phead;
int middle=0;
L_phead=NULL;
R_phead=NULL;
if(left<right)
{
middle=(left+right)/2;
L_phead=cut_list(list,left,middle);
R_phead=cut_list(list, middle+1,right);
return sort(L_phead,R_phead);
}
else
{
return list[left];
}
}
struct ListNode* mergeKLists(struct ListNode** lists, int listsLen ) {
return cut_list(lists,0,listsLen-1);
}