实现顺序栈的各种基本运算的算法

内容:实现顺序栈的各种基本运算,完成以下功能

1.初始化栈s

2.判断栈s是否为空

3.依次进栈元素a,b,c,d,e

4.判断栈s是否非空

5.输出出栈序列

6.判断栈s是否非空

7.释放栈

#include<stdio.h>
#include<malloc.h>
#define Maxsize 50
typedef char ElemType;
char Z;
typedef struct
{
    ElemType data[Maxsize];
    int top;
}SqStack;//声明顺序栈类型

void InitStack(SqStack*& s)
{
    s = (SqStack*)malloc(sizeof(SqStack));
    s->top = -1;
}//初始化栈

void DestroyStack(SqStack*& s)
{
    free(s);
}//销毁栈
bool StackEmpty(SqStack *s)
{
    return(s->top == -1);
} //判断栈是否为空
bool Push(SqStack*& s, ElemType e)
{
    if (s->top == Maxsize - 1)
        return false;
    s->top++;
    s->data[s->top] = e;
    return true;
}//进栈
bool Pop(SqStack*& s, ElemType& e)
{
    if (s->top == -1)
        return false;
    e = s->data[s->top];
    s->top--;
    return true;
}//出栈
bool GetTop(SqStack* s, ElemType& e)
{
    if (s->top == -1)
        return false;
    e = s->data[s->top];
    return true;
} //取栈顶元素

int main()
{
    SqStack* s;
    printf("顺序栈的基本运算\n");
    printf("初始化栈\n");
    InitStack(s);
    printf("判断栈s是否非空: %s\n", (StackEmpty(s) ? "空" : "非空"));
    printf("依次进栈元素a,b,c,c,d,e\n");
    Push(s, 'a');
    Push(s, 'b');
    Push(s, 'c');
    Push(s, 'd');
    Push(s, 'e');
    printf("判断栈s是否非空: %s\n", (StackEmpty(s) ? "空" : "非空"));
    printf("依次出栈");
    while (s->top!=-1)
    {
        Pop(s, Z);
        printf("%c", Z);
    }
    printf("\n");
    printf("判断栈s是否非空: %s\n", (StackEmpty(s) ? "空" : "非空"));
    printf("释放栈\n");
    DestroyStack(s);

}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值