2-11. 两个有序链表序列的合并(15)
时间限制
500 ms
内存限制
80000 kB
代码长度限制
8000 B
判题程序
Standard
已知两个非降序链表序列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<stdio.h>
#define SIZE 100000
int main()
{
int n,count=0;
int i,j;
int a[SIZE];
while(1)
{
scanf("%d",&n);
if(n==-1)
break;
a[count]=n;
count++;
}
while(1) //插入排序
{
scanf("%d",&n);
if(n==-1)
break;
i=0;
while(n>a[i])
i++;
for(j=count;j>i;j--)
a[j]=a[j-1];
a[j]=n;
count++;
}
if(count==0)
{
printf("NULL");
return 0;
}
for(i=0;i<count;i++)
{
if(i==0)
printf("%d",a[i]);
else
printf(" %d",a[i]);
}
}
用数组实现,SIZE的大小不好确定,总是有段错误,可以考虑用向量#include<stdio.h>
#define SIZE 20000
int a1[SIZE],a2[SIZE],a3[SIZE*2]; //数组a1,a2; 数组3是合并后的数组
int size1=0,size2=0,size3=0; //数组a1,a2,a3的实际大小
int main()
{
int n;
int i,j;
while(1)
{
scanf("%d",&n);
if(n==-1)
break;
a1[size1]=n;
size1++;
}
while(1)
{
scanf("%d",&n);
if(n==-1)
break;
a2[size2]=n;
size2++;
}
int j1=0,j2=0;
int size3=0;
//合并算法, 有点像归并算法
while(j1!=size1 && j2!=size2) //a1,a2有一个数组到了尽头, 就终止循环
{
if(a1[j1]<=a2[j2])
{
//printf("%d<%d\n",a1[j1],a2[j2]);
a3[size3]=a1[j1];
j1++;
}
else
{
//printf("%d>=%d\n",a1[j1],a2[j2]);
a3[size3]=a2[j2];
j2++;
}
size3++;
}
for(i=j1;i<size1;i++) //a1有剩余
{
a3[size3]=a1[j1];
size3++;
}
for(i=j2;i<size2;i++) //a2有剩余
{
a3[size3]=a2[i];
size3++;
}
if(size3==0)
{
printf("NULL");
return 0;
}
for(i=0;i<size3;i++)
{
if(i==0)
printf("%d",a3[i]);
else
printf(" %d",a3[i]);
}
}
最后一种是用向量实现,测试全部通过。
#include<stdio.h>
#include<vector>
using namespace std;
vector<int> a1,a2,a3; //向量a1,a2; 向量3是合并后的向量
int main()
{
int n;
int i,j;
while(1)
{
scanf("%d",&n);
if(n==-1)
break;
a1.push_back(n);
}
while(1)
{
scanf("%d",&n);
if(n==-1)
break;
a2.push_back(n);
}
int j1=0,j2=0;
int size1=a1.size(), size2=a2.size();
//合并算法, 有点像归并算法
while(j1!=size1 && j2!=size2) //a1,a2有一个数组到了尽头, 就终止循环
{
if(a1[j1]<=a2[j2])
{
//printf("%d<%d\n",a1[j1],a2[j2]);
a3.push_back(a1[j1]);
j1++;
}
else
{
//printf("%d>=%d\n",a1[j1],a2[j2]);
a3.push_back(a2[j2]);
j2++;
}
}
for(i=j1;i<size1;i++) //a1有剩余
{
a3.push_back(a1[j1]);
j1++;
}
for(i=j2;i<size2;i++) //a2有剩余
{
a3.push_back(a2[j2]);
j2++;
}
int size3=a3.size();
if(size3==0)
{
printf("NULL");
return 0;
}
for(i=0;i<size3;i++)
{
if(i==0)
printf("%d",a3[i]);
else
printf(" %d",a3[i]);
}
}