1 #include<stdio.h> 2 #include<malloc.h> 3 #include<stdlib.h> 4 5 #define TRUE 1 6 #define FALSE 0 7 #define OK 1 8 #define ERROR 0 9 #define INFEASIBLE -1 10 #define OVERFLOW -2 11 12 #define LIST_INIT_SIZE 100 //存储空间初始分配量 13 #define LISTINCREMENT 10 //存储空间不够时,动态增加的分配量 14 15 typedef int ElemType; 16 typedef int Status; 17 18 typedef struct { 19 ElemType *elem; //存储空间基地址 20 int length; //当前长度 21 int listsize; //当前分配的存储容量,即有多少个ElemType空间 22 }SqList; 23 24 Status InitList_Sq(SqList *L); //初始化线性表 25 Status ListInsert_Sq(SqList *L,int i,ElemType e); //插入操作 26 Status ListDelete_Sq(SqList *L,int i,ElemType *e); //删除操作 27 void TraverseList_Sq(SqList L); //遍历线性表 28 29 int main() 30 { 31 SqList L; 32 ElemType e; 33 int i,n = 10; 34 InitList_Sq(&L); 35 for(i= 1; i <= n; i++) 36 { 37 ListInsert_Sq(&L,i,i); //插入10个元素,1,2,3,...,10 38 } 39 TraverseList_Sq(L); 40 41 printf("输入要删除的位置:"); 42 scanf("%d",&i); 43 ListDelete_Sq(&L,i,&e); 44 TraverseList_Sq(L); 45 printf("e=%d\n",e); 46 47 printf("输入要插入的位置和数值:"); 48 scanf("%d %d",&i,&e); 49 ListInsert_Sq(&L,i,e); 50 TraverseList_Sq(L); 51 return 0; 52 } 53 54 Status InitList_Sq(SqList *L) 55 { 56 //分配存储空间100*sizeof(ElmeType),并把存储空间基地址返回给L->elem 57 L->elem = (ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType)); 58 if(!L->elem) exit(OVERFLOW); 59 L->length = 0; 60 //初始化存储空间容量为100 61 L->listsize = LIST_INIT_SIZE; 62 return OK; 63 } 64 65 //在第i个位置前,插入新元素,i是从1开始变化的 66 Status ListInsert_Sq(SqList *L,int i,ElemType e) 67 { 68 //插入位置不合理 69 if(i < 1 || i> L->length+1) return ERROR; 70 //存储空间不足,增加分配 71 if(L->length >= L->listsize ) 72 { 73 ElemType *newbase = (ElemType *) realloc (L->elem, 74 (L->listsize + LISTINCREMENT)*sizeof(ElemType)); 75 if(!newbase) exit(OVERFLOW); 76 L->elem = newbase; 77 L->listsize += LISTINCREMENT; 78 } 79 ElemType *q = &(L->elem[i-1]); 80 ElemType *p; 81 for(p = &(L->elem[L->length-1]); p >= q; --p) 82 { 83 *(p+1)=*p; 84 } 85 *q = e; 86 (L->length)++; 87 return OK; 88 } 89 90 Status ListDelete_Sq(SqList *L,int i,ElemType *e) 91 { 92 //删除位置不合理 93 if(i < 1 || i > L->length) return ERROR; 94 ElemType *p = &(L->elem[i-1]); 95 *e = *p; 96 ElemType *q = &(L->elem[L->length-1]); 97 for(++p; p <= q; p++) 98 { 99 *(p-1) = *p; 100 } 101 (L->length)--; 102 return OK; 103 } 104 105 void TraverseList_Sq(SqList L) 106 { 107 int i; 108 printf("线性表元素为:"); 109 for(i = 0; i <= L.length-1; i++) 110 { 111 printf("%d,",L.elem[i]); 112 } 113 printf("\n"); 114 }