C++顺序存储的线性表
来源:http://blog.csdn.net/creazyapple/article/details/7931830
/* * 顺序存储的线性表 */ #include <stdio.h> #define OK 1 #define ERR 0 #define LIST_INIT_SIZE 100 #define LIST_INCREMENT 10 #define ElemType char typedef struct { ElemType *elem; int length;//元素个数 int listSize;//总容量 } SqList; int InitList(SqList *aList) { aList->elem = (ElemType *)malloc(sizeof(ElemType)*LIST_INIT_SIZE); if(NULL == aList->elem)return ERR; aList->listSize = LIST_INIT_SIZE; aList->length = 0; return OK; } int ListInsert(SqList *aList,ElemType e,int index) { int i; if( index<0 || index>aList->length ){ printf("Error : Insert %c to wrong position %d\n",e,index); return ERR;//中间不允许存在空位 } if( aList->listSize <= aList->length ) { aList->elem = (ElemType *)realloc(aList->elem, sizeof(ElemType)*aList->listSize+LIST_INCREMENT); if(NULL == aList->elem) return ERR; aList->listSize += LIST_INCREMENT; } printf("Insert %c to position %d\n",e,index ); i = aList->length; while(i>index) { aList->elem[i] = aList->elem[i-1]; i--; } aList->elem[index] = e; aList->length++; return OK; } int ListDelete(SqList *aList,ElemType *e,int index) { int i = index; if(i<0 || i>=aList->length)return ERR; *e = aList->elem[index]; i = index; while(i<aList->length-1) { aList->elem[i] = aList->elem[i+1]; i++; } aList->length--; return OK; } int ListTraverse(SqList aList) { int i=0; while(i < aList.length){ printf("%c\t",aList.elem[i]); i++; } printf("\n"); return OK; } int main(int argc, char *argv[]) { SqList aList ; char element; int position; InitList( &aList ); while(1){ printf("Please input element and position to insert in (input ; to quit) :\n"); scanf("%1s,%d",&element,&position); if(';' == element) break; ListInsert(&aList,element,position); } ListDelete(&aList,&element,0); ListTraverse(aList); printf("length :%d . \n",aList.length); return OK; }