#include <iostream>
#include <stdio.h>
#include <malloc.h>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAXSIZE 100
#define exit
typedef char ElemType;
typedef struct
{
ElemType* base;//栈底指针
ElemType* top;//栈顶指针
int stacksize;//栈可用的最大容量
} SqStack;
void InitStack(SqStack& S)
{
//构造一个空栈S
S.base = new ElemType[MAXSIZE];
if (!S.base)
exit(OVERFLOW);
S.top = S.base;
S.stacksize = MAXSIZE;
}
bool StackEmpty(SqStack& S) //判断栈是否为空
{
if (S.top == S.base)
{
printf("顺序栈为空\n");
return true;
}
else
{
printf("顺序栈为非空\n");
return false;
}
}
bool Push(SqStack& S, ElemType e) //顺序栈进栈
{
if (S.top - S.base == S.stacksize)
return ERROR;
*S.top++ = e;
return OK;
}
bool Pop(SqStack& S, ElemType& e) //顺序栈出栈
{
if (S.top == S.base)
return ERROR;
e = *--S.top;
return OK;
}
void DestroyStack(SqStack& S) //销毁
{
free(S.base);
printf("顺序栈已销毁");
}
bool GetTop(SqStack& S) //取栈顶元素
{
if (S.top != S.base)
return *(S.top - 1);
}
void InitStack(SqStack& S);
bool StackEmpty(SqStack& S);
bool Push(SqStack& S, ElemType e);
bool Pop(SqStack& S, ElemType& e);
void DestroyStack(SqStack& S);
bool GetTop(SqStack& S, ElemType& e);
int main()
{
SqStack S;
ElemType e;
InitStack(S);
printf("顺序栈已初始化\n");
StackEmpty(S);
Push(S, 'a');
Push(S, 'b');
Push(S, 'c');
Push(S, 'd');
Push(S, 'e');
printf("已插入元素a,b,c,d,e,判断栈是否为空?\n");
StackEmpty(S);
/***
将顺序栈S栈内的
全部元素出栈,并
输出出栈结果,求教!
***/
while (!StackEmpty(S))
{
ElemType e;
Pop(S, e);
printf("取出元素%c \n", e);
}
}
顺序栈//代码
猜你喜欢
转载自blog.csdn.net/weixin_44811068/article/details/102984489
今日推荐
周排行