#include <stdio.h> #include <malloc.h> #define OK 1 #define OVERFLOW -1 #define ERROR 0 #define LIST_INIT_SIZE 100 #define LISTINCREMENT 10 typedef int ElemType; typedef int Status; typedef struct{ ElemType * elem; int length; int listsize; }sqlist; //////////////////////////初始化 Status InitList_sq(sqlist * L){ L->elem = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType)); if(!L->elem) return OVERFLOW; L->length = 0; L->listsize = LIST_INIT_SIZE; return OK; } //////////////////////////插入 Status ListInsert_Sq(sqlist * L, int i, ElemType e){ ElemType * newbase, * p, * q; if(i < 1 || i > L->length + 1) return ERROR; if(L->length >= L->listsize){ newbase = (ElemType *)realloc(L->elem, (L->listsize + LISTINCREMENT) * sizeof(ElemType)); if(!newbase) return OVERFLOW; L->elem = newbase; L->listsize = L->listsize + LISTINCREMENT; } q = &(L->elem[i-1]); for(p = &(L->elem[L->length-1]); p>=q; --p) *(p+1) = *p; *q = e; ++L->length; return OK; } //////////////////////////往表中输入数值 void input_data(sqlist * L){ int i, n=5; ElemType e; printf("请输入顺序表的数据: "); for(i=1; i<=n; i++){ printf("请输入第%d个数据 : ", i); scanf("%d", &e) ; if(!ListInsert_Sq(L,i,e)){ printf("赋值失败!!"); break; } } printf("输入完毕!"); printf("表La的数据为: "); for(i = 1; i <= L->length; i++) printf("e[%d]=%d ", i-1, L->elem[i-1]); printf("长度: %d ", L->length); } ////////////////////////////////合并 Status MergeList(sqlist * La,sqlist * Lb,sqlist * Lc){ int * pa, * pa_last, * pb, * pb_last, * pc; pa = La->elem; pb = Lb->elem; Lc->listsize = Lc->length = La->length + Lb->length; pc = Lc->elem = (ElemType *)malloc(Lc->listsize*sizeof(int)); if (!Lc->elem) return OVERFLOW; pa_last = La->elem + La->length - 1; pb_last = Lb->elem + Lb->length - 1; while(pa <= pa_last) *pc++ = *pa++; while(pb <= pb_last) *pc++ = *pb++; return OK; } //////////////////////////////////主函数 int main(void){ sqlist La, Lb, Lc; int i; ElemType e; printf("/*-------------合并操作----------------* "); if(InitList_sq(&La)){ printf("La初始化成功 "); printf("La长度: %d ", La.length); printf("La容量: %d ", La.listsize); } else printf("La初始化错误!"); printf("请输入La中数据 "); input_data(&La); printf("输入完毕 "); if(InitList_sq(&Lb)){ printf("Lb初始化成功 "); printf("Lb长度: %d ", La.length); printf("Lb容量: %d ", La.listsize); } else printf("Lb初始化错误!"); printf("请输入Lb中数据 "); input_data(&Lb); if(MergeList(&La, &Lb, &Lc)) printf("合并成功 "); for(i = 1; i <= Lc.length; i++) printf("e[%d]=%d ", i-1, Lc.elem[i-1]); printf("长度: %d ", Lc.length); return 0; }