voidaddEle(struct MineArrayList *list, int index, int element) { // 判断是否需要扩容 if (list->count + 1 > list->capacity) { extendList(list); } // 判断传入的下标是否有效 if (index >= list->capacity || index < 0) { printf("This index is invalid!!!"); return; } // 单独拿出数组操作 int *arr = list->arr; // 在指定位置插入元素 for (int i = list->count; i > index; i--) { arr[i] = arr[i - 1]; } arr[index] = element; list->count++; }
voidaddLastEle(struct MineArrayList *list, int element) { addEle(list, list->count, element); }
voidaddFirstEle(struct MineArrayList *list, int element) { addEle(list, 0, element); }
voidremoveEle(struct MineArrayList *list, int index) { // 先判断 List 是否为空 if (list->count == 0) { printf("This list is empty, there is no element to delete!!!"); } // 判断传入的下标是否有效 if (index >= list->capacity || index < 0) { printf("This index is invalid!!!"); return; } // 单独拿出数组操作 int *arr = list->arr; // 删除指定位置元素(数据往前移动,count - 1) for (int i = index; i < list->count - 1; ++i) { arr[i] = arr[i + 1]; } list->count--; // 判断是否需要缩容 if (list->count <= list->capacity / 4) { reduceList(list); } }
/** * 扩容 * @param list */ voidextendList(struct MineArrayList *list) { int *newArr = (int *) calloc(list->capacity * 2, sizeof(int)); int *oldArr = list->arr; for (int i = 0; i < list->count; ++i) { newArr[i] = oldArr[i]; } free(oldArr); list->capacity = list->capacity * 2; list->arr = newArr; }
/** * 缩容 * @param list */ voidreduceList(struct MineArrayList *list) { int *newArr = (int *) calloc(list->capacity / 4, sizeof(int)); int *oldArr = list->arr; for (int i = 0; i < list->capacity / 2; ++i) { newArr[i] = oldArr[i]; } free(oldArr); list->capacity = list->capacity / 2; list->arr = newArr; }
voidshow(conststruct MineArrayList *list) { printf("The capacity of arraylist is %d.\n", list->capacity); printf("There %d elements in this list.\n", list->count); printf("All elements of MineArrayList:\n"); for (int i = 0; i < list->count; ++i) { printf("index-%d : %d\n", i, list->arr[i]); } }