voidaddEle(struct ArrayStack *stack, int index, int element) { // 判断是否需要扩容 if (stack->count + 1 > stack->capacity) { extendList(stack); } // 判断传入的下标是否有效 if (index >= stack->capacity || index < 0) { printf("This index is invalid!!!"); return; } // 单独拿出数组操作 int *data = stack->data; // 在指定位置插入元素 for (int i = stack->count; i > index; i--) { data[i] = data[i - 1]; } data[index] = element; stack->count++; }
voidaddLastEle(struct ArrayStack *stack, int element) { addEle(stack, stack->count, element); }
voidremoveEle(struct ArrayStack *stack, int index) { // 先判断 List 是否为空 if (stack->count == 0) { printf("This list is empty, there is no element to delete!!!"); } // 判断传入的下标是否有效 if (index >= stack->capacity || index < 0) { printf("This index is invalid!!!"); return; } // 单独拿出数组操作 int *data = stack->data; // 删除指定位置元素(数据往前移动,count - 1) for (int i = index; i < stack->count - 1; ++i) { data[i] = data[i + 1]; } stack->count--; // 判断是否需要缩容 if (stack->count <= stack->capacity / 4) { reduceList(stack); } }
voidextendList(struct ArrayStack *stack) { int *newData = (int *) calloc(stack->capacity * 2, sizeof(int)); int *oldData = stack->data; for (int i = 0; i < stack->count; ++i) { newData[i] = oldData[i]; } free(oldData); stack->capacity = stack->capacity * 2; stack->data = newData; }
voidreduceList(struct ArrayStack *stack) { int *newData = (int *) calloc(stack->capacity / 4, sizeof(int)); int *oldData = stack->data; for (int i = 0; i < stack->capacity / 2; ++i) { newData[i] = oldData[i]; } free(oldData); stack->capacity = stack->capacity / 2; stack->data = newData; }
intmain() { structArrayStack * stack = newStack(5); for (int i = 0; i < 40; ++i) { push(stack, i); } show(stack); printf("======================\n"); for (int i = 0; i < 5; ++i) { int value = pop(stack); printf("pop value is %d\n", value); } printf("======================\n"); show(stack); for (int i = 0; i < 30; ++i) { int value = pop(stack); } printf("======================\n"); show(stack); return0; }