#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node *next;
}*STU,nodes;
STU creat_list(STU head)
{
STU p1,p;
int i,num;
head->next=NULL;
p1=head;
printf("请输入要创建的节点个数: \n");
scanf("%d",&num);
printf("请输入节点数据: \n");
for(i=0;i<num;i++)
{
p=(STU)malloc(sizeof(nodes));
scanf("%d",&p->data);
p1->next=p;
p1=p;
}
p->next=NULL;
return head;
}
STU Merge(STU head1,STU head2)
{
STU p1,p2,news,nhead,np;
nhead=(STU)malloc(sizeof(nodes));
nhead->next=NULL;
np=nhead;
p1=head1->next;
p2=head2->next;
while(p1&&p2)
{
if(p1->data>p2->data)
{
news=(STU)malloc(sizeof(nodes));
news->data=p2->data;
np->next=news;
news->next=NULL;
np=news;
p2=p2->next;
}
else
{
news=(STU)malloc(sizeof(nodes));
news->data=p1->data;
np->next=news;
news->next=NULL;
np=news;
p1=p1->next;
}
}
while(p1!=NULL)
{
news=(STU)malloc(sizeof(nodes));
news->data=p1->data;
np->next=news;
np=news;
news->next=NULL;
p1=p1->next;
}
while(p2!=NULL)
{
news=(STU)malloc(sizeof(nodes));
news->data=p2->data;
np->next=news;
np=news;
news->next=NULL;
p2=p2->next;
}
printf("合并完成!\n");
return nhead;
}
void put(STU head)
{
STU p=head->next;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
if(head->next=NULL)
{
printf("空链表!\n");
exit(0);
}
}
int main()
{
STU head1,head2,news;
head1=(STU)malloc(sizeof(nodes));
head2=(STU)malloc(sizeof(nodes));
creat_list(head1);
creat_list(head2);
news=Merge(head1,head2);
put(news);
return 0;
}
单链表合并
最新推荐文章于 2022-11-15 15:14:39 发布