5-51 两个有序链表序列的合并 (20分)
已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的并集新非降序链表S3。
输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用-1−1表示序列的结尾(-1−1不属于这个序列)。数字用空格间隔。
输出格式:
在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。
输入样例:
1 3 5 -1
2 4 6 8 10 -1
输出样例:
1 2 3 4 5 6 8 10
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node * merge(struct node * head1, struct node * head2)//合并链表
{
struct node * p, *q, *r, *t;
p = head1->next;
q = head2->next;
free(head2);
head1->next = NULL;
r = head1;//用head1作为新链表的头结点
while(p&&q)//当两个链表都不为空的时候
{
if(p->data>=q->data)//按照非降序排列
{
t = q->next;
q->next = NULL;
r->next = q;
r = q;
q = t;
}
else
{
t = p->next;
p->next = NULL;
r->next = p;
r = p;
p = t;
}
}
if(p)//若有一个不是空,将其接入后面
r->next = p;
else
r->next = q;
return head1;
};
void show(struct node * head)//输出
{
struct node * p;
p = head->next;
while(p)
{
while(p->next)
{
printf("%d ", p->data);
p = p->next;
}
printf("%d\n", p->data);
p = p->next;
}
}
int main()
{
int a;
struct node * head, *p, *q;
head = (struct node *)malloc(sizeof(struct node));
p = (struct node*)malloc(sizeof(struct node));
p = head;
while(scanf("%d", &a)&&a!=-1)//每次输入都要顺序插入
{
q = (struct node*)malloc(sizeof(struct node));
q->data = a;
q->next = NULL;
p->next = q;
p = q;
}
struct node * head2;
head2 = (struct node *)malloc(sizeof(struct node));
p = head2;
while(scanf("%d", &a)&&a!=-1)
{
q = (struct node*)malloc(sizeof(struct node));
q->data = a;
q->next = NULL;
p->next = q;
p = q;
}
head = merge(head, head2);
if(head->next==NULL)//如果新链表是空的
printf("NULL\n");
else//否则,输出
show(head);
return 0;
}