题目描述
已知线性表 LA 和 LB 中的数据元素按值非递减有序排列,现要求将 LA 和 LB 归并为一个新的线性表 LC, 且 LC 中的数据元素仍然按值非递减有序排列。例如,设LA=(3,5,8,11) ,LB=(2,6,8,9,11,15,20) 则
LC=(2,3,6,6,8,8,9,11,11,15,20)
算法描述如下:
从上述问题要求可知,LC中的数据元素或是LA中的数据元素,或是LB中的数据元素,则只要先设LC为空表,然后将LA或LB中的元素逐个插入到LC中即可。为使LC中元素按值非递减有序排列,可设两个指针 i 和 j 分别指向LA和LB中某个元素,若设 i 当前所指的元素为 a,j 所指的元素为 b,则当前应插入到 LC 中的元素 c 为 c = a < b ? a : b显然,指针 i 和 j 的初值均为1(实际写代码时往往是从 0 开始的),在所指元素插入 LC 之后,在 LA 或者 LB 中顺序后移。上述归并算法如下图:
图:有序列表有序插入算法
输入格式
有多组测试数据,每组测试数据占两行。第一行是集合A,第一个整数m(0<=m<=100)代表集合A起始有m个元素,后面有m个非递减排序的整数,代表A中的元素。第二行是集合B,第一个整数n(0<=n<=100)代表集合B起始有n个元素,后面有n个非递减排序的整数,代表B中的元素。每行中整数之间用一个空格隔开。
输出
每组测试数据只要求输出一行,这一行含有 m+n个来自集合 A和集合B 中的元素。结果依旧是非递减的。每个整数间用一个空格隔开。
样例输入
4 3 5 8 11
7 2 6 8 9 11 15 20
样例输出
2 3 5 6 8 8 9 11 11 15 20
提示[+]
*** 提示已隐藏,点击上方 [+] 可显示 ***
# include "stdio.h"
# include "stdlib.h"
# define List_Size 200
struct data{
int num;
};
typedef struct
{
struct data num[List_Size];
int last;
} SqList;
SqList *Create_List(SqList *L)
{
L = (SqList *) malloc (sizeof(SqList));
L ->last = -1;
return L;
}
void Get_Data(SqList *L,int i,int *e)
{
*e=L->num[i].num;
}
void Insert_List(SqList *L)
{
struct data d;
if(L->last == List_Size-1)
exit(0);
else
{
scanf("%d",&d.num);
L->last++;
L ->num[L->last].num = d.num;
}
}
void Insert(SqList *L,int k,int e)
{
if(L->last == List_Size-1)
exit(0);
else
{
L->last++;
L ->num[k].num = e;
}
}
int Locat_Data(SqList *L,int e)
{
int i;
for(i=0;i<=L->last;i++)
{
if(L->num[i].num==e)
return 1;
}
return 0;
}
void Show_List(SqList *L)
{
int i;
for(i=0;i<=L->last;i++)
if(i==L->last)
printf("%d",L->num[i].num);
else
printf("%d ",L->num[i].num);
printf("\n");
}
void Merge_List(SqList *La,SqList *Lb,SqList *Lc)
{
int i=0,j=0,k=0,ai,bj;
while((i<=La->last)&&(j<=Lb->last))
{
Get_Data(La,i,&ai);
Get_Data(Lb,j,&bj);
if(ai<=bj)
{
Insert(Lc,k++,ai);
++i;
}
else
{
Insert(Lc,k++,bj);
++j;
}
}
while(i<=La->last)
{
Get_Data(La,i++,&ai);
Insert(Lc,k++,ai);
}
while(j<=Lb->last)
{
Get_Data(Lb,j++,&bj);
Insert(Lc,k++,bj);
}
}
int main()
{
int m,n,i,flag;
while(scanf("%d",&m)!=EOF)
{
SqList *La,*Lb,*Lc;
La = Create_List(La);
Lb = Create_List(Lb);
Lc = Create_List(Lc);
for(i=0;i<m;i++)
Insert_List(La);
scanf("%d",&n);
for(i=0;i<n;i++)
Insert_List(Lb);
Merge_List(La,Lb,Lc);
Show_List(Lc);
}
return 0;
}