兩個有序連結清單序列的合并
- 題目
- 答案
- 注意
題目
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAzNfRHLGZkRGZkRfJ3bs92YsYTMfVmepNHL45EShFHeywEMW1mY1RzRapnTtxkb5ckYplTeMZTTINGMShUYfRHelRHLwEzX39GZhh2css2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xyayFWbyVGdhd3LcV2Zh1Wa9M3clN2byBXLzN3btg3Pn5GcuMDNxIDOycTMxADNwEjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
答案
#include<stdio.h>
#include<malloc.h>
struct Array{
int data;
struct Array *next;
};
int main()
{
struct Array *head,*head1,*pa,*pb,*head2,*p,*temp;
head1=(struct Array *)malloc(sizeof(struct Array));
head1->next=NULL;
p=head1;
int t;
while(1)
{
scanf("%d",&t);
if(t==-1) break;
else
{
temp=(struct Array *)malloc(sizeof(struct Array));
temp->data=t;
temp->next=NULL;
p->next=temp;
p=p->next;
}
}
head2=(struct Array *)malloc(sizeof(struct Array));
head2->next=NULL;
p=head2;
while(1)
{
scanf("%d",&t);
if(t==-1) break;
else
{
temp=(struct Array *)malloc(sizeof(struct Array));
temp->data=t;
temp->next=NULL;
p->next=temp;
p=p->next;
}
}
head=(struct Array *)malloc(sizeof(struct Array));
head->next=NULL;
p=head;
pa=head1->next;
pb=head2->next;
while(pa&&pb)
{
if(pa->data<pb->data)
{
p->next=pa;
p=p->next;
pa=pa->next;
}
else
{
p->next=pb;
p=p->next;
pb=pb->next;
}
}
p->next=pa?pa:pb;
head1->next=NULL;
head2->next=NULL;
int flag=0;
if(head->next==NULL)
{
printf("NULL");
return 0;
}
while(head->next)
{
if(flag==0)
{
printf("%d",head->next->data);
flag=1;
}
else printf(" %d",head->next->data);
head=head->next;
}
}
注意
如果malloc報錯,就在開頭加上這一句