数据结构之栈的动态顺序存储实现-c语言版

#include <stdio.h>
#define STACK_SIZE 100  /*栈初始向量大小 */
#define STACK_INCREMENT 10 /*  空间分配增量 */
typedef int ElemType;
typedef int Status;

#define OK 1
#define ERROR -1

/* 栈的类型定义 */
typedef struct sqstack
{
    ElemType *bottom;  /* 栈不存在时未NULL */
    ElemType *top; /* 栈顶指针 */
    int stackSize; /* 当前已分配空间,已元素为单位 */
}*Pstack;

Status Init_Stack(Pstack S);
Status Push(Pstack S,ElemType e);
Status Pop(Pstack S,ElemType *e);


/* 栈的初始化 */
Status Init_Stack(Pstack S)
{
    S->bottom=(ElemType *)malloc(STACK_SIZE *sizeof(ElemType));
    if(!S->bottom) return ERROR;
    S->top = S->bottom;  /* 栈空时栈顶和栈底相同 */
    S->stackSize = STACK_SIZE;
    return OK;
}

/* 压栈(元素进栈)*/
Status Push(Pstack S,ElemType e)
{
    if(S->top-S->bottom >=S->stackSize-1)
    {
        S->bottom = (ElemType *)realloc(S->bottom,(STACK_INCREMENT+STACK_SIZE)*sizeof(ElemType));
        /* 栈满追加存储空间 */
        if(!S->bottom) return ERROR;
        S->top = S->bottom+S->stackSize-1;
        S->stackSize += STACK_INCREMENT;
    }
    *(S->top) = e; S->top++; /* 栈顶指针加1, e成为新的栈顶*/
    return OK;
}

/* 弹栈(元素出栈)*/
Status Pop(Pstack S,ElemType *e)
{
    if(S->top == S->bottom)
    {
        return ERROR; /* 栈空,返回失败标记 */
    }
    S->top--;
    *e = *(S->top);
    return OK;
}


int main(void)
{
    int i =0,j=0;
    Pstack stack;
    Init_Stack(stack);

    while(i<10)
    {
        ElemType e = i;
        Push(stack,e);
        i++;
    }

    while(j<10)
    {
        ElemType e1;
        Pop(stack,&e1);
        printf("%d,",e1);
        j++;
    }
    return 0;
}




以上代码是纯c语言,我是在code::blocks上执行通过的。大家可以参考。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

coding的乐趣

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值