//操作结果 C = AUB
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#define LIST_INIT_SIZE 10 //动态内存的初始分配量
#define LISTINCREMENT 2
typedef struct SqList
{
int *elem;
int length;
int listsize;
}SqList;
bool InitList(SqList *L); //线性表的初始化
bool ListInsert(SqList *L,int pos,int e); //在第pos个位置插入e
bool ListTraverse(SqList *L); //输出线性表中的元素
int comp(int c1,int c2);
void MergeList(SqList La,SqList Lb, SqList * Lc);
int main()
{
SqList La, Lb, Lc;
int j;
InitList(&La); //在表La中插入5个元素
for(j = 1; j <= 5; j++)
ListInsert(&La,j,j);
printf("La = ");
ListTraverse(&La); //输出La的元素
InitList(&Lb);
for(j = 1; j <= 5; j++) //在表Lb中插入5个元素
ListInsert(&Lb,j,2*j);
printf("Lb = ");
ListTraverse(&Lb);
MergeList(La,Lb,&Lc);
printf("Lc = ");
ListTraverse(&Lc);
return 0;
}
bool InitList(SqList *L) //线性表的初始化
{
L->elem = (int *)malloc(LIST_INIT_SIZE*sizeof(int));
if(L->elem == NULL)
{
printf("内存分配失败 程序终止!\n");
exit(-1);
}
L->length = 0;
L->listsize = LIST_INIT_SIZE;
return 0;
}
bool ListInsert(SqList *L,int pos,int e) //在第pos个位置插入e
{
int * newbase, *p, *q;
if(pos < 1 || pos > L->listsize) //pos值不合法
return false;
if(L->length >= L->listsize) //当前存储空间已满 增加分配
{
newbase = (int *)realloc(L->elem,(L->listsize + LISTINCREMENT)*sizeof(int));
if(newbase == NULL)
{
printf("内存分配失败 程序终止!\n");
exit(-1);
}
L->elem = newbase;
L->listsize += LISTINCREMENT;
}
q = L->elem + pos - 1;
for(p = L->elem + L->listsize - 1; p >= q; p--) //插入位置及插入位置之后的元素右移
*(p+1) = *p;
*q = e; //插入e
L->length++;
return true;
}
bool ListTraverse(SqList *L) //输出线性表中的元素
{
int *p;
int i;
p = L->elem;
for(i = 1; i <= L->length; i++)
printf("%d ",*p++);
printf("\n");
return true;
}
void MergeList(SqList La,SqList Lb, SqList * Lc)
{
int *pa, *pa_last, *pb, *pb_last, *pc;
pa = La.elem;
pb = Lb.elem;
Lc->listsize = La.length + Lb.length;
pc = Lc->elem = (int *)malloc(Lc->listsize*sizeof(int));
if(Lc->elem == NULL)
{
printf("内存分配失败 程序终止!\n");
exit(-1);
}
pa_last = La.elem + La.length - 1;
pb_last = Lb.elem + Lb.length - 1;
while(pa <= pa_last && pb <= pb_last) //表La和表Lb均为非空
{
switch(comp(*pa,*pb))
{
case 0: pb++;
case 1: *pc++ = *pa++;
break;
case -1: *pc++ = *pb++;
}
}
while(pa <= pa_last) //表La非空 表Lb为空
*pc++ = *pa++;
while(pb <= pb_last)
*pc++ = *pb++;
Lc->length = pc - Lc->elem;
}
int comp(int c1,int c2)
{
int i;
if(c1 < c2)
i = 1;
else if(c1 = c2)
i = 0;
else
i = -1;
return i;
}
程序执行结果: