C语言数据结构——栈

typedef int STDataType;
typedef struct Stack
{
    STDataType* arr;
    int top;        // 栈顶
    int capacity;  // 容量 
}ST;
// 初始化栈 
void STInit(ST* ps);
// 入栈 
void STPush(ST* ps, STDataType x);
// 出栈 
void STPop(ST* ps);
// 获取栈顶元素 
STDataType STTop(ST* ps);
// 获取栈中有效元素个数 
int STSize(ST* ps);
// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0 
bool STEmpty(ST* ps);
// 销毁栈 
void STDestroy(ST* ps);


void STInit(ST* ps) {
    assert(ps);
    ps->top = 0;
    ps->capacity = 2;
    ps->arr = (STDataType*)malloc(ps->capacity * sizeof(STDataType));
    if (ps->arr == NULL) {
        perror("malloc is fail!\n");
        exit(-1);
    }
}


void STDestroy(ST* ps) {
    assert(ps);


    free(ps->arr);
    ps->arr = NULL;
    ps->top = 0;
    ps->capacity = 0;
}


void STPush(ST* ps, STDataType x) {
    assert(ps);
    //位置不够就扩容
    if (ps->top == ps->capacity) {
        ps->capacity *= 2;
        STDataType* tmp = (STDataType*)realloc(ps->arr, sizeof(STDataType) * ps->capacity);
        if (tmp == NULL) {
            perror("realloc is fail!\n");
            exit(-1);
        }
        ps->arr = tmp;
        printf("capacity expand is success!\n");
    }
    ps->arr[ps->top] = x;
    ps->top++;
}


STDataType STTop(ST* ps) {
    assert(ps);
    assert(!STEmpty(ps));
    //top为栈顶元素的下一个
    return ps->arr[ps->top - 1];
}


void STPop(ST* ps) {
    assert(ps);
    if (!STEmpty(ps)) {
        ps->top--;
    }
    else {
        printf("栈已空!\n");
    }
}


bool STEmpty(ST* ps) {
    assert(ps);
    //if (ps->top == 0) {
    //  return true;
    //}
    //else {
    //  return false;
    //}


    return ps->top == 0;
}


int STSize(ST* ps) {
    assert(ps);
    return ps->top;
}

你可能感兴趣的:(数据结构,c语言)