关于我自己对顺序栈的一些浅薄的理解
包括:栈的建立、初始化、入栈、出栈、输出等一系列操作、
不多说,直接上代码:
#include <iostream>
#define MAXSIZE 100
#define OVERFLOW -2
#define OK 1
#define TRUE 1
#define FALSE 0
#define ERROR 0
using namespace std;
int i,j,k,n;
int p,e;
typedef int SElemType;
typedef int Status;
typedef struct
{
SElemType *base;//栈底指针
SElemType *top;//栈顶指针
int stacksize;//栈可用最大容量
}SqStack;
//栈的初始化
Status InitStack(SqStack &S)
{
S.base = new SElemType[MAXSIZE];//分配地址
if(!S.base) exit(OVERFLOW);
S.top = S.base;//栈顶指针与栈底指针指向相同
S.stacksize = MAXSIZE;
return OK;
}
//栈是否为空
Status StackEmpty(SqStack &S)
{
if(S.base == S.top)//判断栈顶和栈底是否相等 ,相等为空
return true;
else
return false;
}
//栈的长度
int StackLength(SqStack &S)
{
return S.top - S.base; //两指针相减为元素个数
}
//入栈
Status Push(SqStack &S,SElemType &e)
{
if(S.top - S.base == S.stacksize) return ERROR;//栈满(上溢)
*S.top++ = e;//当前位置放入元素后,栈顶指针向上移动一格
return OK;
}
//出栈
Status Pop(SqStack &S,SElemType &e)
{
if(S.top == S.base) return ERROR;//栈空(下溢)、
e = *--S.top;//栈顶指针下移再取元素
return OK;
}
//清空栈元素
Status ClearStack(SqStack &S)
{
if(S.base) S.top = S.base;//将两指针相等即可清空栈元素(皇帝的清空)
return OK;
}
//销毁栈
Status DestoryStack(SqStack &S)
{
if(S.base)//栈中有元素不为空
{
delete S.base;//删除指针
S.stacksize = 0;//容量清空
S.base = S.top = NULL;//指针置空
}
return OK;
}
void test01()
{
SqStack S;//创建栈
int n,p; //接收变量
SElemType e;
cout << "1.初始化" << endl << endl;
InitStack(S);//初始化
cout << "2.判断栈是否为空" << endl;
if(StackEmpty(S)) cout << "栈为空!" << endl << endl;
else cout << "栈非空!" << endl << endl;
cout << "3.栈的长度" << endl;
cout << "栈的长度为:" << StackLength(S) << endl << endl;
cout << "4.入栈" << endl;
cout << "请输入要入栈的元素个数:"; cin >> n;
cout << "请输入入栈的元素:";
for(int i = 1; i <= n; ++i)
{
cin >> e;
p = Push(S,e);//入栈
}
if(p) cout << "入栈成功!" << endl << endl;
cout << "5.出栈" << endl;
for(int i = 0; i < S.stacksize; ++i)
{
p = Pop(S,e);//出栈
if(p) cout << e << " ";
}
cout << endl << endl;
cout << "6.清空栈元素" << endl;
if(ClearStack(S)) cout << "成功清除栈元素!" << endl << endl;
cout << "7.销毁栈表" << endl;
if(DestoryStack(S)) cout << "成功销毁栈!" << endl << endl;
}
int main(void)
{
test01();//测试案例
return 0;
}