7-2 两个有序链表序列的合并
分数 20
全屏浏览题目
切换布局
作者 DS课程组
单位 浙江大学
已知两个非降序链表序列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
代码长度限制
16 KB
时间限制
1500 ms
内存限制
128 MB
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
typedef int ElemType;
typedef int Status;
typedef struct LNode{
ElemType data;
struct LNode *next;
}*LinkList;
LinkList InitList_L(LinkList L){
L=(LinkList)malloc(sizeof(struct LNode));
L->next=NULL;
return L;
}
void ListInsert_L(LinkList L,ElemType e){
LinkList node;
node=(LinkList)malloc(sizeof(struct LNode));
node->data=e;
node->next=NULL;
L->next=node;
}
LinkList MergeList_L(LinkList A,LinkList B,LinkList C){
LinkList a,b,c;
a=A->next;
b=B->next;
C=c=A;
while(a&&b){
if(a->data<=b->data){
c->next=a;
c=a;
a=a->next;
}
else {
c->next=b;
c=b;
b=b->next;
}
}
c->next=a?a:b;
free(B);
return C;
}
Status Print(LinkList L){
LinkList p=L;
if(p->next==NULL)
return -1;
p=p->next;
int i=0;
while(p){
i++;
if(i==1)
printf("%d",p->data);
else printf(" %d",p->data);
p=p->next;
}
}
int main(){
LinkList A,B,C,a,b;
int x;
A = InitList_L(A);
B = InitList_L(B);
C = InitList_L(C);
a = A;
b = B;
while(1){
scanf("%d",&x);
if(x==-1)
break;
ListInsert_L(A,x);
A = A->next;
}
while(1){
scanf("%d",&x);
if(x==-1)
break;
ListInsert_L(B,x);
B = B->next;
}
C = MergeList_L(a,b,C);
if(C->next==NULL)
printf("NULL");
else
Print(C);
}