本程序实现将两个元素非递减排列的顺序表合并
以下程序用VC++6.0调试,确认正确无误。
#include
#include
#define MaxSize 100
#define listincrement 10
#define begin_size 5 //表初始长度
typedef int ElemType;
typedef struct //定义
{
ElemType *elem;
int length;
int listsize;
}SeqList;
void Init_SeqList(SeqList *L) //创建空表
{
L->elem = (int*)malloc(MaxSize*sizeof(ElemType));
if(!L->elem) exit(0);
L->length = 0;
L->listsize = MaxSize;
}
void Put_SeqList(SeqList *L) //打印表
{
ElemType *begin, *end;
begin = L->elem;
end = &(L->elem[L->length-1]);
if(begin == end) exit(0);
for(; begin < end ; begin++) printf("%d->",*begin);
printf("%d\n",*end);
}
void Insert_SeqList(SeqList *L, int i, ElemType x) //插入元素
{
ElemType *newbase, *insertptr, *p;
if(i < 1 || i > L->length+1) exit(0);
if(L->length >= L->listsize)
{
newbase=(ElemType*)realloc(L->elem, (L->listsize+listincrement)*sizeof(ElemType));
if(!newbase) exit(0);
L->elem = newbase;
L->listsize += listincrement;
}
insertptr = &(L->elem[i-1]);
p = &(L->elem[L->length-1]);
for(;p >= insertptr; p--)
*(p+1) = *p;
*insertptr = x;
L->length++ ;
}
/********以下为合并算法部分*******/
void Merge_SeqList(SeqList La, SeqList Lb, SeqList *Lc) //已知La,Lb的元素非递减排列
{
ElemType *pa, *pb, *pc, *pa_last, *pb_last;
pa = La.elem; pb = Lb.elem;
Lc->length = La.length + Lb.length; Lc->listsize = Lc->length;
pc = (ElemType*)malloc(Lc->listsize*sizeof(ElemType)); //分配存储空间
if(!Lc->elem) exit(0);
Lc->elem = pc; //存储地址
pa_last = La.elem + La.length-1;
pb_last = Lb.elem + Lb.length-1;
while(pa <= pa_last && pb <= pb_last) //归并
if(*pa <= *pb) *pc++ = *pa++;
else *pc++ = *pb++;
while(pa <= pa_last) *pc++ = *pa++;
while(pb <= pb_last) *pc++ = *pb++;
}
/**********以下为main函数*******/
int main() //实现创建两个顺序表,然后将两个表归并
{
SeqList La, Lb, Lc;
ElemType x;
int i;
Init_SeqList(&La); //初始化
Init_SeqList(&Lb);
Init_SeqList(&Lc);
printf("请输入表La\n"); //创建La Lb
for(i = 1; i <= begin_size; i++)
{
scanf("%d",&x);
Insert_SeqList(&La,i,x);
}
printf("请输入表Lb\n");
for(i = 1; i <= begin_size; i++)
{
scanf("%d",&x);
Insert_SeqList(&Lb,i,x);
}
Merge_SeqList(La,Lb,&Lc); //归并
Put_SeqList(&Lc);
return 0;
}