7-1 两个有序链表序列的合并 (20分)
已知两个非降序链表序列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
AC:
直接用数组写的,但是这个数组大小,真是测试了好多次,最后才通过的。s3正常说应该是s1和s2大小的和,但是由于不知道s1和s2的大小,只能三个开一样大了。
#include<iostream>
using namespace std;
#define MAX 9999999
int s1[MAX],s2[MAX],s3[MAX];
int main() {
int x;
int i=0,j=0,k=0;
while(cin>>x&&x>0) {
s1[i++]=x;
}
while(cin>>x&&x>0) {
s2[j++]=x;
}
if(i==0&&j==0) {
cout<<"NULL"<<endl;
return 0;
}
int p=0,s=0;
while(i&&j) {
if(s1[p]<s2[s]) {
s3[k++]=s1[p++];
i--;
} else {
s3[k++]=s2[s++];
j--;
}
}
while(i) {
s3[k++]=s1[p++];
i--;
}
while(j) {
s3[k++]=s2[s++];
j--;
}
int cnt=0;
for(int i=0; i<k; i++) {
if(cnt++)
cout<<" ";
cout<<s3[i];
}
return 0;
}
哪里错了???
#include<iostream>
using namespace std;
#define MAX 999999
int main() {
int i=0,j=0;
int x,y;
int s1[MAX],s2[MAX],s3[MAX];
cin>>x;
while(x>0) {
s1[i++]=x;
cin>>x;
}
cin>>y;
while(y>0) {
s2[j++]=y;
cin>>y;
}
if(i==0&&j==0) {
cout<<"NULL";
return 0;
}
int cnt=0;
int m=0,n=0,k=0;
while(m<i&&n<j) {
if(s1[m]<s2[n]) {
s3[k++]=s1[m++];
} else {
s3[k++]=s2[n++];
}
}
while(m<i) {
s3[k++]=s1[m++];
}
while(n<j) {
s3[k++]=s2[n++];
}
for(int q=0; q<i+j; q++) {
if(cnt++)
cout<<" ";
cout<<s3[q];
}
return 0;
}