书中的代码:
1 #include <iostream> 2 using namespace std; 3 4 #define MaxSize 50 5 typedef int ElemType; 6 typedef struct 7 { 8 ElemType data[MaxSize]; 9 int length; 10 }Sqlist; 11 12 //1.初始化线性表 13 void InitList(Sqlist * &L) 14 { 15 L = (Sqlist *)malloc(sizeof(Sqlist)); 16 L->length = 0; 17 } 18 //2.销毁线性表 19 void DestroyList(Sqlist * &L) 20 { 21 free(L); 22 } 23 //3.判断线性表是否为空 24 bool ListEmpty(Sqlist * &L) 25 { 26 return (L->length == 0); 27 } 28 //4.返回线性表的长度 29 int ListLength(Sqlist * L) 30 { 31 return L->length; 32 } 33 //5.输出线性表 34 void DispList(Sqlist * &L) 35 { 36 for (size_t i = 0; i < L->length; i++) 37 { 38 printf("%d", L->data[i]); 39 printf("\n"); 40 } 41 42 } 43 //6.求线性表中某个数据元素 44 bool GetElem(Sqlist * L, int i, ElemType &e) 45 { 46 if (i <1 || i>L->length) 47 { 48 return false; 49 } 50 e = L->data[i - 1]; 51 return true; 52 } 53 //7.按元素值进行查找 54 int LocateElem(Sqlist * L, ElemType e) 55 { 56 int i = 0; 57 while (i < L->length && L->data[i] != e) 58 { 59 i++; 60 } 61 if (i > L->length) 62 { 63 return 0; 64 } 65 else 66 { 67 return i + 1; 68 } 69 } 70 //8.插入数据元素 71 bool ListInsert(Sqlist * &L, int i, ElemType e) 72 { 73 int j = 0; 74 75 if (i<1 || i >L->length+1) 76 { 77 return false; 78 } 79 i--; 80 for (j = L->length; j > i; j--) 81 { 82 L->data[j] = L->data[j - 1]; 83 } 84 L->data[i] = e; 85 L->length++; 86 87 88 return true; 89 } 90 //9.删除数据元素 91 bool ListDelete(Sqlist * &L, int i, ElemType &e) 92 { 93 int j = 0; 94 if (i<1 || i>L->length) 95 { 96 return false; 97 } 98 i--; 99 e = L->data[i]; 100 for (j = i; j < L->length - 1; j++) 101 { 102 L->data[j] = L->data[j + 1]; 103 } 104 L->length--; 105 return true; 106 } 107 108 int main() 109 { 110 Sqlist * L; 111 InitList(L);//初始化顺序表 112 ListInsert(L, 1, 1); 113 ListInsert(L, 2, 2); 114 ListInsert(L, 3, 3); 115 ListInsert(L, 4, 4); 116 ListInsert(L, 5, 5); 117 DispList(L); 118 printf("当前的长度:%d",ListLength(L)); 119 getchar(); 120 return 0; 121 }