输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−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>
typedef struct Node{
struct Node *next;
int data;
}node;
node *scanner(){
node *head = NULL; //不带头节点
int a;
node *p;
while(scanf("%d",&a))
{
if(a!=-1){
node *current = (node *)malloc(sizeof(node));
current->data = a;
if(!head){
head = current;
}
else{
p->next = current;
}
p = current; //记录当前节点值,便下次输入
}
else{
p->next = NULL;
break;
}
}
return head;
}
int main(){
node *list1,*list2; // 定义两个数组
list1 = scanner();
list2 = scanner();
int flag = 0; //用于控制空格输入
while(list1&&list2){
if(list1->data>list2->data){ //小的直接输出(也可以以此建立第三条链再输出)
if(flag){
printf(" ");
}
else{
flag = 1;
}
printf("%d",list2->data);
list2 = list2->next;
}
else{
if(flag){
printf(" ");
}
else{
flag = 1;
}
printf("%d",list1->data);
list1 = list1->next;
}
}
/*list1不空*/
while(list1){
if(flag){
printf(" ");
}
else{
flag = 1;
}
printf("%d",list1->data);
list1 = list1->next;
}
/*list2不空*/
while(list2){
if(flag){
printf(" ");
}
else{
flag = 1;
}
printf("%d",list2->data);
list2 = list2->next;
}
if(!flag){
printf("NULL");
}
return 0;
}