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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值