1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
| #include "sqlist.h" void initSqList(SqList *&sl); bool isEmpty(SqList *sl); void addCapacity(SqList *&sl); void destorySqList(SqList *&sl); int getLength(SqList *sl); void printList(SqList *sl); void deleteElement(SqList *&sl, int i, ElemType &e); void insertElement(SqList *&sl, int i, ElemType e); void getElementByIndex(SqList *sl, int i, ElemType &e); int getElementIndex(SqList *&sl, ElemType e); int main(){ SqList *sl; ElemType ele; initSqList(sl); insertElement(sl, 1, 10); insertElement(sl, 2, 20); insertElement(sl, 3, 30); insertElement(sl, 4, 40);
deleteElement(sl,4,ele); printList(sl);
printf("元素%d的位置是:%d\n",20, getElementIndex(sl,20));
getElementByIndex(sl, 2, ele); printf("第%d个元素是:%d\n",2, ele); return 0; }
void initSqList(SqList *&sl) { sl = (SqList *)malloc(MAX_SIZE*sizeof(SqList)); sl->length = 0; }
bool isEmpty(SqList *sl) { return (sl->length == 0); }
void addCapacity(SqList *&sl) { sl = (SqList *)realloc(sl,(sl->length + INCREMENT_SIZE)); if (!sl) { printf("扩容失败"); } sl->length += INCREMENT_SIZE; }
void destorySqList(SqList *&sl) { free(sl); }
int getLength(SqList *sl) { return sl->length; }
void printList(SqList *sl) { int i; if (isEmpty(sl)) { printf("List is empty\n"); } for ( i = 0; i < sl->length; i++){ printf("%d\t",sl->data[i]); } }
void insertElement(SqList *&sl, int i, ElemType e) { if (i<1 || i>sl->length+1) { printf("插入的位置不合法\n"); return; } if (sl->length == MAX_SIZE) { addCapacity(sl); } int j; for (j=sl->length-1; j>=i - 1; j--){ sl->data[j + 1] = sl->data[j]; } sl->data[i - 1] = e; sl->length++; }
void deleteElement(SqList *&sl, int i, ElemType &e) { if (i<1 || i>sl->length) { printf("插入的位置不合法\n"); return; } e = sl->data[i - 1]; int j; for (j = i; j < sl->length; j++) { sl->data[j - 1] = sl->data[j]; } sl->length--; }
int getElementIndex(SqList *&sl, ElemType e) { int i = 0; while (i < sl->length && sl->data[i] != e) { i++; } if (i < sl->length) { return i + 1; }else { return -1; } }
void getElementByIndex(SqList *sl, int i, ElemType &e) { if (i<1 || i>sl->length) { printf("访问的位置不合法"); return; } e = sl->data[i - 1]; }
void deleteEle_1(SqList *sl, ElemType x) { int i; ElemType e; while ((i = getElementIndex(sl, x)) > 0) { deleteElement(sl, i, e); } }
void deleteEle_2(SqList *sl, ElemType x) { int k = 0, i; for (i = 0; i < sl->length; i++) { if (sl->data[i] != x) { sl->data[k] = sl->data[i]; k++; } } sl->length = k; }
|