顺序表应用5:有序顺序表归并
Time Limit: 100MS
Memory Limit: 800KB
Problem Description
已知顺序表A与B是两个有序的顺序表,其中存放的数据元素皆为普通整型,将A与B表归并为C表,要求C表包含了A、B表里所有元素,并且C表仍然保持有序。
Input
输入分为三行:
第一行输入m、n(1<=m,n<=10000)的值,即为表A、B的元素个数;
第二行输入m个有序的整数,即为表A的每一个元素;
第三行输入n个有序的整数,即为表B的每一个元素;
第一行输入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
Hint
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#define Maxsize 10000
using namespace std;
typedef int element;
typedef struct
{
element *elem;
int length;
int listsize;
} Sqlist;
int InitList(Sqlist &L)
{
L.elem = new element[Maxsize];
if(!L.elem)
return -1;
L.length = 0;
L.listsize = Maxsize;
return 1;
}
void creat(Sqlist &L, int l)
{
for(int i = 0; i < l; i++)
{
cin >> L.elem[i];
L.length++;
}
L.listsize = Maxsize;
}
void hehe(Sqlist &L1, Sqlist &L2, Sqlist &L)
{
L.elem = new element[Maxsize*2];
if(!L.elem)
exit(0);
L.length=L1.length+L2.length;
int i=0,j=0,k=0;
while(i < L1.length&&j < L2.length)
{
if(L1.elem[i] <= L2.elem[j])
{
L.elem[k++] = L1.elem[i];
i++;
}
else
{
L.elem[k++] = L2.elem[j];
j++;
}
}
if(i < L1.length)
{
while(i < L1.length)
{
L.elem[k++] = L1.elem[i++];
}
}
if(j < L2.length)
{
while(j < L2.length)
{
L.elem[k++] = L2.elem[j++];
}
}
}
void display(Sqlist &L)
{
for(int i = 0; i < L.length; i++)
if(i != L.length-1)
cout << L.elem[i] << " ";
else
cout << L.elem[i] << endl;
}
int main()
{
int n, m;
Sqlist L1, L2, L;
cin >> n >> m;
InitList(L1);
InitList(L2);
creat(L1, n);
creat(L2, m);
hehe(L1, L2, L);
display(L);
return 0;
}