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

/**
*   实现顺序栈各种基本运算的算法
*   目的:
*       领会顺序栈存储结构和掌握顺序栈中各种基本运算算法设计
*   主要功能:
*       1、初始化栈s
*       2、判断栈s是否非空
*       3、依次进栈元素a、b、c、d、e
*       4、判断栈s是否非空
*       5、输出栈序列
*       6、释放栈
*/

#include <stdio.h>
#include <malloc.h>
#include <stdbool.h>

#define MAX_SIZE 100

typedef char ElemType;
typedef struct
{
    ElemType data[MAX_SIZE];
    int top; //栈顶指针
}SeqStack; //声明顺序栈类型

/*----------------------初始化顺序栈------------------------*/
static void init_stack(SeqStack *&s) // 指针的引用
{
    s = (SeqStack *)malloc(sizeof(SeqStack));
    s->top = -1;
}

/*----------------------销毁顺序栈------------------------*/
static void destroy_stack(SeqStack *&s)
{
    free(s);
}

/*----------------------判断栈空否------------------------*/
static bool stack_empty(SeqStack *s)
{
    return (s->top == -1);
}

/*----------------------进栈------------------------*/
static bool push(SeqStack *&s, ElemType e)
{
    if(s->top == (MAX_SIZE - 1)) // 栈满的情况,栈上溢出
        return false;

    s->top++;
    s->data[s->top] = e;

    return true;
}

/*----------------------出栈------------------------*/
static bool pop(SeqStack *&s, ElemType &e) // 指针的引用
{
    if(s->top == -1) // 栈为空的情况,即栈下溢出
        return false;

    e = s->data[s->top];
    s->top--;

    return true;
}

/*----------------------取栈顶元素------------------------*/
static bool get_top(SeqStack *s, ElemType &e)
{
    if(s->top == -1) // 栈为空的情况,即栈下溢出
        return false;

    e = s->data[s->top];

    return true;
}

int main(int argc, char *argv[])
{
    ElemType e;
    SeqStack *s;

    printf("顺序栈s的基本运算如下:\n");
    printf("  (1)初始化栈s\n");
    init_stack(s);
    printf("  (2)栈为%s\n",(stack_empty(s) ? "空" : "非空"));
    printf("  (3)依次进栈元素a,b,c,d,e\n");
    push(s, 'a');
    push(s, 'b');
    push(s, 'c');
    push(s, 'd');
    push(s, 'e');
    printf("  (4)栈为%s\n",(stack_empty(s) ? "空" : "非空"));
    printf("  (5)出栈序列:");
    while(!stack_empty(s))
    {
        pop(s, e);
        printf("%c ", e);
    }
    printf("\n");
    printf("  (6)栈为%s\n",(stack_empty(s) ? "空" : "非空"));
    printf("  (7)释放栈\n");
    destroy_stack(s);

    return 0;
}

运算结果:

顺序栈s的基本运算如下:
  (1)初始化栈s
  (2)栈为空
  (3)依次进栈元素a,b,c,d,e
  (4)栈为非空
  (5)出栈序列:e d c b a
  (6)栈为空
  (7)释放栈

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值