编辑代码

#include <stdio.h>
#include "windows.h"

typedef int E;

struct stack {
    E *array;
    int capacity;   //栈的容量
    int top;    //用来表示栈顶的元素,这里指向元素的index值,也可以表示栈里面有多少个元素
};

typedef struct stack *Stack;

// 栈的初始化方法
BOOL initStack(Stack stack) {
    stack->array = malloc(sizeof(E) * 10);
    if (stack->array == NULL) return 0;
    stack->capacity = 10;
    stack->top = -1; //栈没有元素则为-1
    return 1;
}

void expansion(Stack stack) {
    int newCapacity = stack->capacity * 2;
    E *newArr = realloc(stack, sizeof(E) * newCapacity);
    if (newArr == NULL) {
        printf("栈满扩容失败");
        return;
    }
    stack->array = newArr;
    stack->capacity = newCapacity;
}

BOOL pushStack(Stack stack, E element) {
    if (stack->capacity == stack->top + 1) expansion(stack);
    stack->array[++stack->top] = element;
    return 1;
}

BOOL isEmpty(Stack stack){
    return stack->top == -1;
}

E popStack(Stack stack) {
    if (stack->top == -1) return 0;
    return stack->array[stack->top--];
}

int main() {

}