已知两个非降序链表序列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
思路:
首先,建立链表a,b;其次,对两个链表合并;最后输出。
1.设置函数建立链表p->data=a;str->next=p;str=p;head标记第一个数据,return head;
2.两个链表的合并,先判断是否有空表,有空直接返回另一个表,无空的话,判断两链表data大小,小的s->data=小的->data;d->next=s;d=s;head标记的第一个数据,return head
代码:
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *build();
struct node *operate(struct node *a,struct node *b);
int main()
{
struct node *a,*b,*c;
a = build();
b = build();
c = operate(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;
}
return 0;
}
struct node *build()
{
struct node *head=NULL,*str=NULL;
int a;
scanf("%d",&a);
while(a!=-1)
{
struct node *p = (struct node *)malloc(sizeof(struct node));
p->data = a;
p->next = NULL;
if(NULL==head)
head=p;
else
str->next=p;
str = p;
scanf("%d",&a);
}
return head;
};
struct node *operate(struct node *a,struct node *b)
{
struct node *p,*q,*d=NULL;
struct node *s,*head=NULL;
p=a;
q=b;
if(p==NULL)
return q;
if(q==NULL)
return p;
while(p&&q)
{
s=(struct node *)malloc(sizeof(struct node));
if((p->data)<(q->data))
{
s->data=p->data;
s->next=NULL;
p=p->next;
}
else
{
s->data=q->data;
s->next=NULL;
q=q->next;
}
if(head==NULL)
head=s;
else
d->next=s;
d=s;
}
if(p)
d->next=p;
if(q)
d->next=q;
return head;
}










