#include<stdio.h>
#include<stdlib.h>
#define N 5
#define NULL 0
typedef struct LNode
{
struct LNode *next;
int data;
}LNode,*list;
void creatList(list &l,int n)
{
list p,q;
int i;
l=(list)malloc(sizeof(LNode));
p=l; //头节点
for(i=0;i<n;i++)
{
q=(list)malloc(sizeof(LNode));
scanf("%d",&q->data);
p->next=q;
p=q;
}
p->next=NULL;
}
void mergeList(list &la,list &lb,list &lc)
{
list pa,pb,pc;
pa=la->next;
pb=lb->next;
pc=lc=la;
while(pa&&pb)
{
if(pa->data<=pb->data)
{
pc->next=pa;pc=pa;
pa=pa->next;
}
else
{
pc->next=pb;pc=pb;
pb=pb->next;
}
}
pc->next=pa?pa:pb;
free(lb);
}
void print(list la)
{
list p;
p=la->next;
while(p)
{
printf("%d ",p->data);
p=p->next;
}
}
int main()
{
list la,lb,lc;
printf("create two lists contain %d elements\n",N);
creatList(la,N);
creatList(lb,N);
mergeList(la,lb,lc);
print(lc);
}
合并两个链表
最新推荐文章于 2024-09-01 21:07:46 发布