/*
有序表的合并---用顺序表实现
*/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <stdbool.h>
#define MAXSIZE 100
typedef int ElemType;
typedef struct SqList{
ElemType * elem;
int length;
}SqList;
/*
顺序表的初始化
*/
void InitList_Sq(SqList * L){
L->elem = (ElemType * )malloc(sizeof(ElemType) * MAXSIZE);
if(!L->elem)exit(-1);
L->length = 0;
}
/*
顺序表元素的插入
*/
int ListInsert_Sq(SqList * L, int i, ElemType e){
if(i < 1 || i > L->length + 1) return -1;
if(L->length == MAXSIZE) return -1;
int j;
for(j = L->length - 1; j >= i - 1; j--){
L->elem[j + 1] = L->elem[j];
}
L->elem[i - 1] = e;
L->length++;
return 1;
}
/*
有序表的合并
*/
void MergeList_Sql(SqList LA, SqList LB, SqList * LC){
//指针pa和pb的初值分别指向两个表的第一个元素
ElemType * pa = LA.elem;
ElemType * pb = LB.elem;
//新表长度为待合并两表的长度和
LC->length = LA.length + LB.length;
//为合并后的新表分配一个数组空间
LC->elem = (ElemType *)malloc(sizeof(ElemType) * LC->length);
//pc指向新表第一个元素
ElemType * pc = LC->elem;
//pa_last指向LA表的最后一个元素。pb_last指向LB表的最后一个元素
ElemType * pa_last = LA.elem + (LA.length - 1);
ElemType * pb_last = LB.elem + (LB.length - 1);
while(pa <= pa_last && pb <= pb_last){
//依次取两个表中值最小的结点
if(*pa <= *pb){
//注意这里的操作:pa地址的值赋给pc指针指向的空间,然后pa地址加一,pc加一
*pc++ = *pa++;
}else{
*pc++ = *pb++;
}
}
//LB表已经到达表尾,将LA中剩余元素加入LC
while(pa <= pa_last) *pc++ = *pa++;
//LA表已经到达表尾,将LB中剩余元素加入LC
while(pb <= pb_last) *pc++ = *pb++;
}
/*
输出用于测试
*/
void Test(SqList * L){
int i;
for(i = 0; i < L->length; i++){
printf("%d ", L->elem[i]);
}
printf("
");
}
int main(){
SqList LA;
SqList LB;
InitList_Sq(&LA);
InitList_Sq(&LB);
//往LA表中插入1~10数字
int i;
for(i = 1; i <= 10; i++){
ListInsert_Sq(&LA, i, i);
}
printf("顺序表LA
");
Test(&LA);
//往LB表中插入5~13数字
for(i = 1; i <= 9; i++){
ListInsert_Sq(&LB, i, i + 4);
}
printf("顺序表LB
");
Test(&LB);
SqList LC;
MergeList_Sql(LA, LB, &LC);
printf("顺序表LC
");
Test(&LC);
return 0;
}