已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的并集新非降序链表S3。
输入格式说明:
输入分2行,分别在每行给出由若干个正整数构成的非降序序列,用-1表示序列的结尾(-1不属于这个序列)。数字用空格间隔。
输出格式说明:
在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出“NULL”。
样例输入与输出:
序号 | 输入 | 输出 |
1 | 1 3 5 -1 2 4 6 8 10 -1 | 1 2 3 4 5 6 8 10 |
2 | 1 2 3 4 5 -1 1 2 3 4 5 -1 | 1 1 2 2 3 3 4 4 5 5 |
3 | -1 -1 | NULL |
#include<stdlib.h>
struct node
{
int num;
struct node *next;
};
struct node *creat(void)
{
struct node *head,*p1,*p2;
head=NULL;
p2=NULL;
p1=(struct node*)malloc(sizeof(struct node));
scanf("%d",&p1->num);
while(p1->num!=-1)
{
if(head==NULL)
head=p1;
else
p2->next=p1;
p2=p1;
p1=(struct node*)malloc(sizeof(struct node));
scanf("%d",&p1->num);
}
if(p2)
p2->next=NULL;
return head;
}
void find(struct node *p1,struct node *p2)
{
int f=0;
if(p1==NULL&&p2==NULL)
{
printf("NULL\n");
return;
}
while(p1!=NULL && p2!=NULL)
{
if(p1->num>=p2->num)
{
if(f==0)
{
printf("%d",p2->num);
f=1;
}
else
printf(" %d",p2->num);
p2=p2->next;
}
else
{
if(f==0)
{
printf("%d",p1->num);
f=1;
}
else
printf(" %d",p1->num);
p1=p1->next;
}
}
while(p1)
{
if(f==0)
{
printf("%d",p1->num);
f=1;
}
else
printf(" %d",p1->num);
p1=p1->next;
}
while(p2)
{
if(f==0)
{
printf("%d",p2->num);
f=1;
}
else
printf(" %d",p2->num);
p2=p2->next;
}
printf("\n");
}
int main()
{
struct node *p1,*p2;
p1=creat();
p2=creat();
find(p1,p2);
return 0;
}