5-51 两个有序链表序列的合并(20分)

来源:互联网 发布:地平线机器人 知乎 编辑:程序博客网 时间:2024/04/30 03:25

已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的并集新非降序链表S3。

输入格式:

输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用-11表示序列的结尾(-11不属于这个序列)。数字用空格间隔。

输出格式:

在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL

输入样例:

1 3 5 -12 4 6 8 10 -1

输出样例:

1 2 3 4 5 6 8 10

#include<iostream>#include<vector>using namespace std;int main(){vector<int> v1,v2;vector<int> :: iterator p1,p2;int x;int flag=0;while(1){       //读入v1 cin>>x;if(x!=-1)v1.push_back(x);elsebreak;}while(1){       //读入v2 cin>>x;if(x!=-1)v2.push_back(x);elsebreak; }for(p1=v1.begin(),p2=v2.begin();p1!=v1.end()&&p2!=v2.end();){if(*p1<*p2){cout<<*p1<<" ";p1++;}else {cout<<*p2<<" "; p2++;}}while(p1!=v1.end()){if(flag)cout<<" ";else flag=1;cout<<*p1;p1++;}while(p2!=v2.end()){if(flag)cout<<" ";else flag=1;cout<<*p2;p2++;}if(v1.size()==0&&v2.size()==0)   //判断是否为空 cout<<"NULL";cout<<endl;return 0;} 


                                             
1 0