题目链接:http://pat.zju.edu.cn/contests/ds/2-11
已知两个非降序链表序列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 |
PS:个人觉得用链表太过繁琐,所以就用vector了,233333333……
代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#include <vector>
vector<int>a, b, c;
int main()
{
int tt;
while(1)
{
scanf("%d",&tt);
if(tt == -1)
break;
a.push_back(tt);
}
while(1)
{
scanf("%d",&tt);
if(tt == -1)
break;
b.push_back(tt);
}
int len1 = a.size();
int len2 = b.size();
int i = 0, j = 0;
while(i < len1 && j < len2)
{
if(a[i] <= b[j])
{
c.push_back(a[i]);
i++;
}
else
{
c.push_back(b[j]);
j++;
}
}
if(i < len1)
{
for(int l = i; l < len1; l++)
{
c.push_back(a[l]);
}
}
else
{
for(int l = j; l < len2; l++)
{
c.push_back(b[l]);
}
}
int len3 = c.size();
if(!len3)
{
printf("NULL\n");
}
else
{
int flag = 0;
for(int i = 0; i < len3; i++)
{
if(flag)
{
printf(" %d",c[i]);
}
else
{
printf("%d",c[i]);
flag = 1;
}
}
printf("\n");
}
return 0;
}
2-11. 两个有序链表序列的合并(15) (ZJUPAT 用vector实现)
原文地址:http://blog.csdn.net/u012860063/article/details/39586719