C语言线性表顺序存储实现 - 归并算法
#include <stdio.h> #include <stdlib.h>
#define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 #define LIST_INIT_SIZE 20 #define LISTINCREAMENT 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_SIZEsizeof(ElemType));
if (!L->elem) exit(OVERFLOW);
L->length=0;
L->listsize= LIST_INIT_SIZE;
return OK;
}
Status ListLength(SqList *L){ return L->length; }
Status ListInsert_Sq(SqList *L, int i, ElemType e) {
ElemType *p,*q,newbase;
if (i<1 || i>L->length+1) return ERROR;
if (L->length+1 >= L-> listsize){
newbase=(ElemType)realloc(L->elem++,(LIST_INIT_SIZE+LISTINCREAMENT)*sizeof(ElemType));
if(!newbase)
return OVERFLOW;
L-> elem=newbase;
L-> listsize+=LISTINCREAMENT;
}
q = &(L->elem[i]);
for (p = &(L->elem[L->length]); p >= q; --p)
*(p+1) = *p;
*q = e;
++L->length;
return OK;
}
Status GetItem(SqList *L,int i,ElemType *e){ if ((i < 1) || (i > L->length)) return ERROR; *e = L->elem[i]; }
void Merge(SqList *La,SqList *Lb,SqList *Lc){ int i=1,j=1,k=0; while(i<=La->length && j<=Lb->length){ if(La->elem[i] <= Lb->elem[j]){ ListInsert_Sq(Lc,++k,La->elem[i++]); } else{ ListInsert_Sq(Lc,++k,Lb->elem[j++]); } } while(i<=La->length){ ListInsert_Sq(Lc,++k,La->elem[i++]); } while(j<=Lb->length){ ListInsert_Sq(Lc,++k,Lb->elem[j++]); } }
Status DestroyList(SqList *L){ free(L); return OK; }
int main(){ SqList *La,*Lb,*Lc; ElemType x,*e; int i,n,choice,position,flag;
La=(SqList *)malloc(sizeof(SqList));
Lb=(SqList *)malloc(sizeof(SqList));
Lc=(SqList *)malloc(sizeof(SqList));
InitList_Sq(La);
InitList_Sq(Lb);
InitList_Sq(Lc);
printf("请输入La中的元素个数:");
scanf("%d",&n);
printf("请输入数据(数字):");
for(i=1;i<=n;i++){
scanf("%d",&x);
ListInsert_Sq(La, i,x);
}
printf("请输入Lb中的元素个数:");
scanf("%d",&n);
printf("请输入数据(数字):");
for(i=1;i<=n;i++){
scanf("%d",&x);
ListInsert_Sq(Lb, i,x);
}
Merge(La,Lb,Lc);
printf("归并后的Lc的元素为:") ;
for(i=1;i<ListLength(Lc);i++)
printf("%d ",Lc->elem[i]);
DestroyList(La);
DestroyList(Lb);
DestroyList(Lc);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/pcxC 著作权归作者所有。请勿转载和采集!