方法一:每两个链表递归合并,合并(lists.length-1)次
链表数据结构
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
struct ListNode
{
int val;
struct ListNode *next;
};
头插法(不带头结点)
struct ListNode* create(int a[], int n)
{
if(n==0) return NULL;
ListNode* p = (ListNode*)malloc(sizeof(ListNode));
p->next=NULL;
p->val = a[0];
int i=1;
ListNode* s,q;
while(i<n){
s = (ListNode*)malloc(sizeof(ListNode));
s->next=p;
s->val=a[i];
p=s;
++i;
}
return p;
}
两个有序链表合并(递归)
struct ListNode* mergeTwo(struct ListNode* A, struct ListNode* B)
{
if(A==NULL){ //指针A指空 则返回B 反之亦然
return B;
}
if(B==NULL){
return A;
}
if(A->val<B->val){ //若A\B均不指向空节点 取小的数 随后递归
A->next = mergeTwo(A->next, B);
return A;
}else{
B->next = mergeTwo(A, B->next);
return B;
}
}
K个有序链表合并
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize)
{
if(listsSize == 0) return NULL;
int i=1;
for(;i<listsSize;++i){ //遍历整个lists 为了节约内存开销 不增加新指针
lists[0]= mergeTwo(lists[0], lists[i]);
}
return list[0];
}
完整代码
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
struct ListNode
{
int val;
struct ListNode *next;
};
struct ListNode* create(int a[], int n)
{
if(n==0) return NULL;
ListNode* p = (ListNode*)malloc(sizeof(ListNode));
p->next=NULL;
p->val = a[0];
int i=1;
ListNode* s,q;
while(i<n){
s = (ListNode*)malloc(sizeof(ListNode));
s->next=p;
s->val=a[i];
p=s;
++i;
}
return p;
}
void disp(ListNode* p){
while(p!=NULL){
printf("%d ", p->val);
p=p->next;
}
printf("\n");
}
struct ListNode* mergeTwo(struct ListNode* A, struct ListNode* B)
{
if(A==NULL){ //指针A指空 则返回B 反之亦然
return B;
}
if(B==NULL){
return A;
}
if(A->val<B->val){ //若A\B均不指向空节点 取小的数 随后递归
A->next = mergeTwo(A->next, B);
return A;
}else{
B->next = mergeTwo(A, B->next);
return B;
}
}
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize)
{
if(listsSize == 0) return NULL;
int i=1;
for(;i<listsSize;++i){ //遍历整个lists 为了节约内存开销 不增加新指针
lists[0]= mergeTwo(lists[0], lists[i]);
}
return list[0];
}
int main()
{
int a[3]={5,4,1};
int b[3]={4,3,1};
int c[2]={6,2};
ListNode *p[3];
p[0] = create(a, 3);
p[1] = create(b, 3);
p[2] = create(c, 2);
ListNode *t = mergeKLists(p, 3);
disp(t);
return 0;
}
方法二:分冶(基于方法一)
struct ListNode* mergeTwo(struct ListNode* A, struct ListNode* B)
{
if(A==NULL){ //指针A指空 则返回B 反之亦然
return B;
}
if(B==NULL){
return A;
}
if(A->val<B->val){ //若A\B均不指向空节点 取小的数 随后递归
A->next = mergeTwo(A->next, B);
return A;
}else{
B->next = mergeTwo(A, B->next);
return B;
}
}
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize)
{
if(listsSize == 0) return NULL;
if(listsSize == 1) return lists[0];
if(listsSize == 2) return mergeTwo(lists[0], lists[1]);
int mid = listsSize/2;
struct ListNode* sub1[mid];
struct ListNode* sub2[listsSize-mid];
int i;
for(i=0;i<mid;++i){
sub1[i] = lists[i];
}
for(i=mid;i<listsSize;++i){
sub2[i-mid] = lists[i];
}
return mergeTwo(mergeKLists(sub1, mid), mergeKLists(sub2, listsSize-mid));
}
2021/06/27