栈(C语言)

顺序栈定义与操作

1. 结构定义(动态分配内存)

typedef struct StackNode
{
    ElemType data;
    struct StackNode* next;
}StackNode, *LinkStack;

2. 栈的初始化

/*
    @description: 初始化顺序栈,初始化长度为MAXSIZE
    @return: 成功true 失败false
    @author: sch
 */
bool InitStack(SqStack &S)
{
    S.elem = (ElemType*) malloc(MAXSIZE * sizeof(ElemType));
    if(!S.elem) exit(OVERFLOW);
    S.stackSize = MAXSIZE;
    S.top = -1;
    return success;
}

3. 判断是否栈空

/*
    @description: 判断顺序栈是否为空
    @return:
    @author: sch
 */
bool isEmpty(SqStack &S)
{
    return (S.top == -1)? true : false;
}

4. 获取栈中元素个数

/*
    @description: 获取顺序栈的元素个数
    @return: 返回元素个数,顺序栈为空返回0
    @author: sch
 */
int StackLength(SqStack &S)
{
    return S.top + 1;
}

5. 向栈中插入栈顶元素

/*
    @description: 向栈中插入新的栈顶元素,顺序栈空间不足时自动增长
    @return: 是否插入成功,成功true, 失败false
    @author: sch
 */
bool Push(SqStack &S, ElemType e)
{
    if(S.stackSize - 1 == S.top)
    {
        ElemType* newElem = (ElemType*) realloc(S.elem, (S.stackSize + INCREMENT) * sizeof(ElemType) );
        if(!newElem) exit(OVERFLOW);
        S.stackSize += INCREMENT;
        S.elem = newElem;
    }
    S.elem[++S.top] = e;
    return success;
}

6. 访问栈顶元素

/*
    @description: 访问栈顶元素并存入元素e中,不改变栈顶指针
    @return:
    @author: sch
 */
bool GetTop(SqStack &S, ElemType &e)
{
    if(S.top == -1) return failed;
    e = S.elem[S.top];
    return success;
}

7. 取出栈顶元素

/*
    @description: 取出栈顶元素
    @return:
    @author: sch
 */
bool Pop(SqStack &S, ElemType &e)
{

    if(S.top == -1) return failed;
    e = S.elem[S.top--];
    return success;
}

8. 遍历顺序栈所有元素

/*
    @description: 遍历栈中元素
    @return: void
    @author: sch
 */
void StackTraverse(SqStack S)
{
    while(~S.top)
    {
        printf("%d\n", S.elem[S.top--]);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值