#include <stdio.h>
#include <malloc.h>
typedef int DataType;
#include "LinList.h"
void main()
{
SLNode *head_A,*head_B,*c,*pa,*pb,*pc;
int i,j,x;
ListInitiate(&head_A);//初始化链表a
ListInsert(head_A,0,1);//a递增链表
ListInsert(head_A,1,3);
ListInsert(head_A,2,5);
ListInsert(head_A,3,7);
pa=head_A->next;
ListInitiate(&head_B);//初始化链表b
ListInsert(head_B,0,2);//b递增链表
ListInsert(head_B,1,3);
ListInsert(head_B,2,6);
ListInsert(head_B,3,8);
ListInsert(head_B,4,9);
ListInsert(head_B,5,12);
pb=head_B->next;
ListInitiate(&c);
/*
设a链表长度为an,b链表长度为bn,
算法时间复杂度:O(an+bn)
*/
while(pb!=NULL && pa!=NULL)
{
pc=(SLNode *)malloc(sizeof(SLNode));
if(pa->data <= pb->data)
{
pc->data=pa->data;
pa=pa->next;
}
else
{
pc->data=(pb->data);
pb=pb->next;
}
//插入步骤
pc->next=c->next;
c->next=pc;
}
if(pa==NULL)//如果a链表读完了,把剩下的b链表赋给c
{
while(pb!=NULL)
{
pc=(SLNode *)malloc(sizeof(SLNode));
pc->data=pb->data;
pb=pb->next;
pc->next=c->next;
c->next=pc;
}
}
else//如果b链表读完了,把剩下的a链表赋给c
{
while(pa!=NULL)
{
pc=(SLNode *)malloc(sizeof(SLNode));
pc->data=pa->data;
pa=pa->next;
pc->next=c->next;
c->next=pc;
}
}
printf("输出a递增链表:\n");
for(i=0;i<ListLength(head_A);i++)
{
ListGet(head_A,i,&x);
printf("%d ",x);
}
printf("\n\n");
printf("输出b递增链表:\n");
for(i=0;i<ListLength(head_B);i++)
{
ListGet(head_B,i,&x);
printf("%d ",x);
}
printf("\n\n");
printf("输出c链表:\n");
for(i=0;i < ListLength(c);i++)
{
ListGet(c,i,&x);
printf("%d ",x);
}
printf("\n\n");
Destroy(&head_A);
Destroy(&head_B);
Destroy(&c);
}