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所存放的元素。
Sample
Input
5 3
1 3 5 6 9
2 4 10
Output
1 2 3 4 5 6 9 10
#include<stdio.h>
#include<malloc.h>
typedef struct
{
int *elem;
int length;
int Size;
}List;
int init(List&L,int n)
{
L.elem = (int*)malloc((n)*sizeof(int));
L.Size = 100000;
return 0;
}
void creat(List&L,int n)
{
L.length = n;
for(int i=0;i<n;i++)
scanf("%d",&L.elem[i]);
}
void guibing(List L1,List L2,List&L)
{
int *t,*t1,*t2,*lt1,*lt2;
t1 = L1.elem;
t2 = L2.elem;
t = L.elem;
lt1 = L1.elem+L1.length-1;
lt2 = L2.elem+L2.length-1;
while(t1<=lt1&&t2<=lt2)
{
if(*t1<=*t2)
*t++ = *t1++;
else
*t++ = *t2++;
}
while(t1<=lt1) {*t++ = *t1++;}
while(t2<=lt2) {*t++ = *t2++;}
}
void show(List &L,int n)
{
int i;
for(i=0;i<n;i++)
if(i==n-1) printf("%d\n",L.elem[i]);
else printf("%d ",L.elem[i]);
}
int main()
{
int t1,t2;
List T1,T2,T;
scanf("%d%d",&t1,&t2);
init(T1,t1);
init(T2,t2);
init(T,t1+t2);
creat(T1,t1);
creat(T2,t2);
guibing(T1,T2,T);
show(T,t1+t2);
return 0;
}