1 #include <stdio.h> 2 #include <stdlib.h> 3 4 #define OK 1 5 #define ERROR 0 6 #define TRUE 1 7 #define FALSE 0 8 #define MAXLEN 100 9 10 typedef int elemType; 11 typedef struct { 12 elemType *data; 13 int len; 14 }LIST; 15 16 //初始化线性表 17 int initList(LIST *L) 18 { 19 L->data = (elemType *)malloc(MAXLEN * sizeof(elemType)); 20 if (L->data == NULL) return ERROR; 21 L->len = 0; 22 return OK; 23 } 24 25 //销毁线性表 26 void destoryList(LIST *L) 27 { 28 if (L->data) free(L->data); 29 } 30 31 //清空线性表 32 void clearList(LIST *L) 33 { 34 L->len = 0; 35 } 36 37 //返回线性表长度 38 int lengthList(LIST *L) 39 { 40 return L->len; 41 } 42 43 int isEmptyList(LIST *L) 44 { 45 if (L->len == 0) return TRUE; 46 else return FALSE; 47 } 48 49 void printList(LIST *L) 50 { 51 int i; 52 for (i = 0; i < L->len; i++) 53 printf("%d ", L->data[i]); 54 printf(" "); 55 } 56 57 //在表头插入元素 58 int insertAtHead(LIST *L, elemType x) 59 { 60 int i; 61 if (L->len == MAXLEN) return ERROR; 62 for (i = L->len; i > 0; i--) 63 L->data[i] = L->data[i-1]; 64 L->data[0] = x; 65 L->len++; 66 return OK; 67 } 68 69 //在表尾插入元素 70 int insertAtEnd(LIST *L, elemType x) 71 { 72 if (L->len == MAXLEN) return ERROR; 73 L->data[L->len] = x; 74 L->len++; 75 return OK; 76 } 77 78 //在指定索引后插入元素 79 int insertAfterIndex(LIST *L, elemType x, int index) 80 { 81 int i; 82 if (L->len == MAXLEN) return ERROR; 83 for (i = L->len + 1; i > index + 1; i++) 84 L->data[i] = L->data[i-1]; 85 L->data[index+1] = x; 86 L->len++; 87 return OK; 88 } 89 90 //删除指定索引处的元素 91 int deleteIndexElem(LIST *L, int index) 92 { 93 int i; 94 if (index < 0 || index >= L->len) return ERROR; 95 for (i = index; i < L->len - 1; i++) 96 L->data[i] = L->data[i+1]; 97 L->len--; 98 return OK; 99 } 100 101 102 //修改指定索引处的元素 103 int updateIndexElem(LIST *L, int index, elemType x) 104 { 105 if (index >= 0 && index < L->len) 106 { 107 L->data[index] = x; 108 return OK; 109 } 110 else return ERROR; 111 } 112 113 //返回指定处的元素 114 elemType getPosElem(LIST *L, int index) 115 { 116 if (index < 0 || index >= L->len) return ERROR; 117 return L->data[index]; 118 } 119 120 //返回某元素的索引 121 int indexList(LIST *L, elemType x) 122 { 123 int i; 124 for (i = 0; i < L->len; i++) 125 if (L->data[i] == x) 126 return i; 127 return ERROR; 128 }