已知兩個非降序鏈表序列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 |
//注意:當我用cin,cout的時候,最后一個case超時,換做scanf,printf之后就AC了,足以證明如果對運行效率要求較高的話還是要選擇stdio的輸入輸出
#include <cstdio>
#include <list>
using namespace std;
int main()
{
list<int> list1;
list<int> list2;
list<int>::iterator it,it1,it2;
int val=0;
bool flag = false;
while(scanf("%d",&val),val!=-1)
list1.push_back(val);
while(scanf("%d",&val),val!=-1)
list2.push_back(val);
if (list1.empty()&&list2.empty())
/*cout<<"NULL"<<endl;*/
printf("NULL\n");
for (it1=list1.begin(),it2=list2.begin();it1!=list1.end()&&it2!=list2.end();)
{
if (*it1 < *it2)
{
if (flag)
/*cout<<" ";*/
printf(" ");
else
flag = true;
/*cout<<*it1;*/
printf("%d",*it1);
it1++;
}
else
{
if (flag)
printf(" ");
else
flag = true;
/* cout<<*it2;*/
printf("%d",*it2);
it2++;
}
}
if (it1==list1.end())
{
while(it2!=list2.end()) {/*cout<<" "<<*it2++;*/ printf(" %d",*it2);it2++;}
}
if (it2==list2.end())
{
while(it1!=list1.end()) {/*cout<<" "<<*it1++;*/printf(" %d",*it1);it1++;}
}
/*cout<<endl;*/
printf("\n");
//system("pause");
return 0;
}
