实验11-2-5 链表拼接
已知两个非降序链表序列S1与S2,设计函数构造出S1与S2合并后的新的非降序链表S3。
输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。
输出格式:
在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。
输入样例:
1 3 5 -1
2 4 6 8 10 -1
输出样例:
1 2 3 4 5 6 8 10
虽然其他方法在这里秒杀链表,但毕竟是考察链表的题,还是规规矩矩用链表解决
AC代码
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
struct Node *build();
struct Node *print(struct Node *a,struct Node *b);
int main()
{
struct Node *a,*b,*c;
a=build();
b=build();
c=print(a,b);
if(!c)
printf("NULL\n");
while(c)
{
if(c->next==NULL)
printf("%d",c->data);
else
printf("%d ",c->data);
c=c->next;
}
}
struct Node *build()
{
int a;
struct Node *head=NULL,*str=NULL;
scanf("%d",&a);
while(a!=-1)
{
struct Node *p=(struct Node*)malloc(sizeof(struct Node));
p->data=a;
p->next=NULL;
if(head==NULL)
head=p;
else
str->next=p;
str=p;
scanf("%d",&a);
}
return head;
}
struct Node *print(struct Node *a,struct Node *b)
{
struct Node *head=NULL,*str=NULL;
while(a&&b)
{
if(a->data<b->data)
{
if(head==NULL)
head=a;
else
str->next=a;
str=a;
a=a->next;
}
else
{
if(head==NULL)
head=b;
else
str->next=b;
str=b;
b=b->next;
}
}
if(a)
while(a)
{
if(head==NULL)
head=a;
else
str->next=a;
str=a;
a=a->next;
}
if(b)
{
while(b)
{
if(head==NULL)
head=b;
else
str->next=b;
str=b;
b=b->next;
}
}
return head;
}