您的位置:首页 > 其它

顺序表应用5:有序顺序表归并

2017-09-29 15:02 295 查看
Problem Description

已知顺序表A与B是两个有序的顺序表,其中存放的数据元素皆为普通整型,将A与B表归并为C表,要求C表包含了A、B表里所有元素,并且C表仍然保持有序。

Input

输入分为三行:

第一行输入m、n(1<=m,n<=10000)的值,即为表A、B的元素个数;

第二行输入m个有序的整数,即为表A的每一个元素;

第三行输入n个有序的整数,即为表B的每一个元素;

Output

输出为一行,即将表A、B合并为表C后,依次输出表C所存放的元素。

Example Input

5 3

1 3 5 6 9

2 4 10

Example Output

1 2 3 4 5 6 9 10

#include <iostream>
using namespace std;
#include <stdio.h>
#include <stdlib.h>
#define listmax 100000
typedef int elemtype;
typedef struct
{
elemtype *elem;
int length;
int listsize;
} list;
void creat(list &L,int n)
{
L.elem=new elemtype[listmax];
L.length=n;
L.listsize=listmax;
}
void input(list &L)
{
int i;
for(i=0; i<L.length; i++)
{
scanf("%d",&L.elem[i]);
}
}
void mer(list &L1,list &L2,list &L3)
{
int i=0,j=0,k=0;
while(i<L1.length&&j<L2.length)
{
if(L1.elem[i]<L2.elem[j])
{
L3.elem[k]=L1.elem[i];
i++;
k++;
}
else//第一次超时了:else if(L1.elem[i]>L2.elem[j])
{
L3.elem[k]=L2.elem[j];
j++;
k++;
}
}
while(i<L1.length)
{
L3.elem[k]=L1.elem[i];
i++;
k++;
}
while(j<L2.length)
{
L3.elem[k]=L2.elem[j];
j++;
k++;
}

}

void output(list &L)
{
int i;
for(i=0; i<L.length-1; i++)
{
printf("%d ",L.elem[i]);
}
printf("%d\n",L.elem[L.length-1]);
}
int main()
{
list L1,L2,L3;
int m,n;
scanf("%d %d",&m,&n);
creat(L1,m);
input(L1);
creat(L2,n);
input(L2);
creat(L3,m+n);//创建新顺序表,才能存。
mer(L1,L2,L3);
output(L3);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据