2-11. 两个有序链表序列的合并
时间限制
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 <iostream>
#include <deque>
using namespace std;
deque<int> a, b, c;
int main()
{
int t;
scanf("%d", &t);
// cin>>t;
while(t != -1)
{
a.push_back(t);
// cin>>t;
scanf("%d", &t);
}
// cin>>t;
scanf("%d", &t);
while(t != -1)
{
b.push_back(t);
scanf("%d", &t);
// cin>>t;
}
if(a.size() + b.size() == 0)
{
cout<<"NULL"<<endl;
return 0;
}
while(a.size() && b.size())
{
if( a.front() < b.front())
{
c.push_back(a.front());
a.pop_front();
}
else
{
c.push_back(b.front());
b.pop_front();
}
}
while(a.size())
{
c.push_back(a.front());
a.pop_front();
}
while(b.size())
{
c.push_back(b.front());
b.pop_front();
}
bool first = true;
while(c.size())
{
if(first)
{
printf("%d", c.front());
// cout<<c.front();
first = false;
}
else
printf(" %d", c.front());
// cout<<" "<<c.front();
c.pop_front();
}
cout<<endl;
return 0;
}