有顺序表LA和LB,其元素均按从小到大的升序排列,编写一个算法,将他们合并成一个顺序表LC,要求LC的元素也按照从小到大的升序排列。
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#define INIT_SIZE 5
#define INCREMENT 4
typedef int ElemType;
typedef struct
{
ElemType *elem;
int length;
int listsize;
}SqList;
int InitList_Sq(SqList *L)
{
L->elem=(ElemType*)malloc(INIT_SIZE*sizeof(ElemType));
if(!L->elem) return 0;
L->length=0;
L->listsize=INIT_SIZE;
return 1;
}
int ListInsert_Sq(SqList *L,int i,ElemType e)
{
int j;
ElemType *newbase;
if(i<0 || i>L->length)return -1;
if(L->length>L->listsize)
{
newbase =(ElemType*)realloc(L->elem,(L->listsize+INCREMENT)*sizeof(ElemType));
if(!newbase)return -1;
L->elem = newbase;
L->listsize+=INCREMENT;
}
for(j=L->length-1;j>=i;j--)
L->elem[j+1] = L->elem[j];
L->elem[i]=e;
++L->length;
return 1;
}
int MergeList_Sq(SqList LA,SqList LB,SqList *LC)
{ int i=0,j=0,k=0;
LC->length=LA.length+LB.length;
LC->elem=(ElemType *)malloc(LC->length* sizeof(ElemType));
if(!LC->elem) return -1;
while(i<LA.length&&j<LB.length)
{
if(LA.elem[i]<=LB.elem[j])LC->elem[k++]=LA.elem[i++];
else LC->elem[k++]=LB.elem[j++];
}
while(i<LA.length) LC->elem[k++]=LA.elem[i++];
while(j<LB.length) LC->elem[k++]=LB.elem[j++];
LC->length=k;
return 1;
}
int main()
{
int n;
SqList la,lb,lc;
InitList_Sq(&la);
InitList_Sq(&lb);
InitList_Sq(&lc);
for(n=0;n<5;n++)
ListInsert_Sq(&la,n,n+1);
for(n=0;n<4;n++)
ListInsert_Sq(&lb,n,n+1);
MergeList_Sq(la,lb,&lc);
for(n=0;n<9;n++)
printf("%d\n",lc.elem[n]);
return 0;
}