1 #include <stdio.h> 2 /*2013-06-19 liuwei*/ 3 typedef int elemtype ; 4 5 #define MAXSIZE 100 6 #define LISTSIZEINCREASE 10 7 #define OK 0 8 #define ERROR -1 9 10 //线性表顺序存储结构描述 11 12 13 typedef struct 14 { 15 elemtype *elem; 16 int length; 17 int listsize; 18 } SqList; 19 20 /*顺序线性表的操作基本操作*/ 21 22 //1.初始化顺序表数据结构 23 int InitList_Sq(SqList& L) 24 { 25 L.elem = (elemtype*)malloc(sizeof(elemtype) * MAXSIZE); 26 if (!L.elem) 27 { 28 return -1; 29 } 30 L.length = 0 31 L.listsize = MAXSIZE; 32 return 0; 33 } 34 35 //2.初始化的相反操作,摧毁整个顺序表 36 37 int DestoryList_Sq(SqList &L) 38 { 39 if (L.elem) 40 { 41 free(L.elem); 42 L.elem = NULL; 43 } 44 L.length = 0; 45 return OK; 46 } 47 48 //3.向顺序表中的第i个位置插入数据元素 49 50 int ListInsert_Sq(SqList& L,int i,elemtype e) 51 { 52 53 if (i < 1 || i > L.length + 1) 54 { 55 return ERROR; 56 } 57 58 if(L.length >= L.listsize) 59 { 60 elemtype *newbase = (elemtype*)realloc(L.elem,(L.listsize + LISTSIZEINCREASE)*sizeof(elemtype)); 61 62 if (!newbase) 63 { 64 return ERROR; 65 } 66 L.elem = newbase; 67 L.listsize += LISTSIZEINCREASE; 68 } 69 70 elemtype *p = &L.elem[L.length - 1]; 71 elemtype *q = &L.elem[i - 1]; 72 for (;p <= q;--p) 73 { 74 *(p+1) = *p; 75 } 76 *q = e; 77 ++L.length; 78 return OK; 79 } 80 81 //4.删除顺序表中第i个数据元素 82 83 int DeleteList_Sq(SqList& L,int i) 84 { 85 86 if (i < 1 || i > L.length) 87 { 88 return ERROR; 89 } 90 elemtype *p = &L.elem[i - 1]; 91 elemtype *q = &L.elem[L.length -1]; 92 for (;p < q;++p) 93 { 94 *p = *(p+1); 95 } 96 --L.length; 97 return OK; 98 } 99 100 //5.清空顺序表中所有的数据元素 101 102 int ClearList_Sq(SqList& L) 103 { 104 L.length = 0; 105 return OK; 106 } 107 108 //6.判断顺序表中的数据元素是否为空,若为空则返回true,若不会空则返回false 109 bool IsEmptyList_Sq(SqList L) 110 { 111 if (L.length == 0) 112 { 113 return true; 114 } 115 return false; 116 } 117 118 //7 取得顺序表中的第i个数据元素 119 elemtype GetElem_Sq(SqList L,int i) 120 { 121 if (i < 1|| i > L.length) 122 { 123 return ERROR; 124 } 125 return L.elem[i-1]; 126 127 } 128 129 //8.判断数据元素是否在线性表中,若在则返回第一次出现的位置,若不在则返回错误 130 131 int LocateList_Sq(SqList L,elemtype e) 132 { 133 int i = 0; 134 for (;i < L.length;++i) 135 { 136 if (L.elem[i] == e) 137 { 138 return i + 1; 139 } 140 } 141 return ERROR; 142 } 143 144 //9.求数据元素的前驱 145 146 elemtype PriorList_Sq(SqList L,int i) 147 { 148 if (i < 2 || i > L.length) 149 { 150 return ERROR; 151 } 152 else 153 return L.elem[i-1]; 154 } 155 156 //10.求数据元素的后继 157 158 elemtype NextList_Sq(SqList L,int i) 159 { 160 if (i < 1 || i > L.length - 1) 161 { 162 return ERROR; 163 } 164 else 165 return L.elem[i + 1]; 166 }
注意: