栈的基本操作

包括构造空栈,销毁栈,把栈置空,检验栈是否为空,求栈的长度,取出栈顶元素,入栈,出栈

#include<stdio.h>
#include<stdlib.h>


#define STACKMAX 100
#define STACKADD 10
#define datatype int

typedef struct
{
    datatype *base;
    datatype *top;
    int stacksize;
}SqStack;

int InitStack(SqStack* S);//初始化,成功返回1
int Destroy(SqStack* S);//销毁栈,成功返回1
int ClearStack(SqStack* S);//把栈置空
int StackEmpty(SqStack* S);//若栈为空返回1,否则返回0
int StackLenth(SqStack* S);//返回栈的元素个数
int GetTop(SqStack* S,datatype* e);//若栈不为空,保存栈顶的元素并返回1;否则返回0
int Push(SqStack* S,datatype e);//插入栈顶元素
int Pop(SqStack* S,datatype* e);//若栈不为空,则删除栈顶元素并保存返回1,否则返回0

int InitStack(SqStack *S)
{
    S->base = (datatype*)malloc(STACKMAX*sizeof(datatype));
    S->top = S->base;
    S->stacksize = STACKMAX;

    return 1;
}

int Destroy(SqStack* S)
{
    free(S->base);
    S->base = NULL;
    S->top = NULL;
    S->stacksize = 0;
    return 1;
}

int ClearStack(SqStack* S)
{
    S->base = S->top;
    return 1;
}

int StackLenth(SqStack* S)
{
    return S->top - S->base;
}

int StackEmpty(SqStack* S)
{
    if(S->base == S->top)
        return 1;
    return 0;
}

int GetTop(SqStack* S,datatype* e)
{
    if(StackEmpty(S))
        return 0;
    *e = *(S->top-1);
    return 1;
}

int Push(SqStack* S,datatype e)
{
    if(S->top - S->base >= S->stacksize)
    {
        S->base = (datatype*)realloc(S->base,(S->stacksize+STACKADD)*sizeof(datatype));
        if(!S->base)
            return 0;
        S->top = S->base + S->stacksize;
        S->stacksize += STACKADD;
    }
    *S->top++ = e;
    return 1;
}

int Pop(SqStack* S,datatype* e)
{
    if(StackEmpty(S))
        return 0;
    *e = *--S->top;
    return 1;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值