线性表的顺序表示和实现模板

xiaoxiao2021-02-28  40

把这代码贴出来只是方便自己日后需用到顺序表时,提供个想法。毕竟这是自己在课堂上实现并理解好的,代码考虑不贴全了

/*线性表的顺序表示和实现*/ #ifndef SQLIST_H_INCLUDED #define SQLIST_H_INCLUDED #include<stdio.h> #include<stdlib.h> #include<malloc.h> #define LIST_INIT_SIZE 100 #define LISTINCREMENT 10 #define TRUE 1 #define ERROR 0 #define FALSE 0 #define OK 1 #define OVERFLOW -2 typedef int Status; typedef int ElemType; 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) exit(OVERFLOW); L.length=0; L.listsize=LIST_INIT_SIZE; return OK; } Status ListLength(SqList l) { return l.length; } Status GetElem(SqList l,int i,ElemType &e) { if(i<1||i>l.length) exit(ERROR); e=*(l.elem+i-1); return OK; } Status ListInsert_Sq(SqList &L,int i,ElemType e) { ElemType *newbase,*q,*p; 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) exit(OVERFLOW); L.elem=newbase; 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; } Status Equal(ElemType a,ElemType b) { if(a==b) return TRUE; else return FALSE; } Status LocateElem(SqList L,ElemType e,Status(*compare)(ElemType,ElemType)) { ElemType *p; int i=1; p=L.elem; while(i<=L.length&&!(*compare)(*p++,e)) ++i; if(i<=L.length) return i; else return 0; } void print(ElemType c) { printf("%d ",c); } Status ListTraverse(SqList l,void(*vi)(ElemType)) { ElemType *p; int i; p=l.elem; for(i=1;i<=l.length;i++) vi(*p++); printf("\n"); return OK; } Status DestroyList(SqList &l) { if (l.elem) free(l.elem); return OK; } Status Clearlist(SqList &l) { l.length=0; return OK; } Status ListDelete(SqList &l,int i,ElemType &e) { ElemType *q,*p; if(i<1||i>l.length) return ERROR; q=&(l.elem[i]); for(p=q;p<=&(l.elem[l.length-1]);p++) *(p-1)=*p; e=*q; -- l.length; return OK; } #endif // SQLIST_H_INCLUDED

转载请注明原文地址: https://www.6miu.com/read-2150359.html

最新回复(0)