/**
* 实现顺序栈各种基本运算的算法
* 目的:
* 领会顺序栈存储结构和掌握顺序栈中各种基本运算算法设计
* 主要功能:
* 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)释放栈