1、建立顺序表
1 void CreateList(SqList*& L, ElemType a[], int n) 2 { 3 int i = 0, j = 0; 4 L = (SqList*)malloc(sizeof(SqList)); 5 while (i < n) 6 { 7 L->data[j] = a[i]; 8 i++; 9 j++; 10 } 11 L->length = n; 12 13 }
2、初始化
1 void InitList(SqList*& L) 2 { 3 L = (SqList*)malloc(sizeof(SqList)); 4 L->length = 0; 5 }
3、销毁
1 void DestroyList(SqList*& L) 2 { 3 free(L); 4 }
4、判断线性表是否为空
1 bool ListEmpty(SqList* L) 2 { 3 return(L->length ==0); 4 5 }
5、求线性表的长度
1 int ListLength(SqList* L) 2 { 3 return(L->length); 4 }
6、输出线性表
1 void DispList(SqList* L) 2 { 3 for (int i = 0; i < L->length; i++) 4 { 5 printf("%d ", L->data[i]); 6 } 7 printf("\n"); 8 9 }
7、求线性表中某个数据元素值
1 bool GetElem(SqList* L, int i, ElemType& e) 2 { 3 if (i<1 || i>L->length) 4 { 5 return false; 6 } 7 else 8 { 9 e = L->data[i-1]; 10 return true; 11 } 12 }
8、按元素值查找
int LocateElem(SqList* L, ElemType e) { int i = 0; while (i < L->length && L->data[i] != e) i++; if (i >= L->length) return 0; else return i + 1; }
9、插入数据元素,注意下标
1 bool ListInsert(SqList*& L, int i, ElemType e) 2 { 3 if (i<1 || i>L->length+1) 4 return false; 5 else 6 { 7 i--; 8 for (int j = L->length; j > i; j--) 9 { 10 L->data[j] = L->data[j - 1]; 11 } 12 L->data[i] = e; 13 L->length++; 14 return true; 15 } 16 }
10、删去数据元素
1 bool ListDelete(SqList*& L, int i, ElemType& e) 2 { 3 if (i<1 || i>L->length ) 4 return false; 5 else 6 { 7 i--; 8 for (int j = i; j < L->length - 1; j++) 9 { 10 L->data[j] = L->data[j + 1]; 11 } 12 e = L->data[i--]; 13 L->length--; 14 return true; 15 } 16 17 }