標籤:style blog color io for re
/* * 動態分配儲存的順序表 */#include <stdio.h>#include <stdlib.h>#define INIT_SIZE 100#define EXPAND_SIZE 50typedef int ElemType;typedef struct { ElemType *head; int len; // 順序表當前元素個數 int size; // 順序表當前最大容量} Sqlist;int init_sqlist(Sqlist *list){ if( (list->head = malloc(INIT_SIZE*sizeof(ElemType))) == NULL ) // 分配初始空間 { printf("init error.\n"); return -1; } list->len = 0; list->size = INIT_SIZE; return 0;}int insert_sqlist(Sqlist *list, int n, ElemType item){ ElemType *t; if( n > list->len+1 || n < 1 ) // 插入位置非法 { printf("insert error, location illegal.\n"); return -1; } if( list->len == list->size ) // 順序表當前容量已經全部用完, 擴容 { t = realloc( list->head, (list->size + EXPAND_SIZE)*sizeof(ElemType) ); if( t == NULL) { printf("realloc error.\n"); return -1; } list->head = t; list->size += EXPAND_SIZE; } for( t = list->head + list->len ; t > (list->head + (n-1)) ; t-- ) // 原第n位置元素及其後的元素依次後移 *t = *(t-1); *t = item; list->len ++; return 0;}int delete_sqlist(Sqlist *list, int n){ ElemType *t; if( n > list->len || n < 1 ) // 刪除位元置非法 { printf("delete error, location illegal.\n"); return -1; } for( t= list->head + (n-1) ; t < list->head + (list->len-1) ; t++ ) // 第n+1位置元素及其後的元素依次前移 *t = *(t+1); list->len --; return 0;}int free_sqlist(Sqlist *list){ free(list->head); return 0;}void print_sqlist(Sqlist list){ int i; for(i=0; i<list.len; i++) printf("%d ", list.head[i]); printf("\n");}int main(void){ Sqlist list; init_sqlist(&list); int i; for( i=1 ; i<=117; i++) insert_sqlist(&list,i,i); print_sqlist(list); delete_sqlist(&list, 5); delete_sqlist(&list, 115); print_sqlist(list); free_sqlist(&list); return 0;}