#include<iostream>
#include<string.h>
#include<stdlib.h>
#include<math.h>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAXSIZE 100
typedef int SElemType;
typedef int Status;
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
//顺序栈的初始化
Status InitStack(SqStack &S)
{// 构造一个空栈 S
S.base = new SElemType[MAXSIZE]; //为顺序栈分配一个最大容量为MAXSIZE的数组空间
if(!S.base)
exit (OVERFLOW); //存储分配失败
S.top = S.base;
S.stacksize = MAXSIZE;
return OK;
}
// 顺序栈的入栈
Status Push(SqStack &S,SElemType &e)
{ // 插入元素e为新的栈顶元素
if(S.top-S.base==S.stacksize)
return ERROR; //栈满
*(S.top++) = e; //元素e压入栈顶,栈顶指针加1
return OK;
}
// 顺序栈的出栈
Status Pop(SqStack &S,SElemType &e)
{// 若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR
if(S.base == S.top)
return ERROR;//栈空
e = *(--S.top); //栈顶指针减1,将栈顶元素赋给e
return OK;
}
// 取顺序栈的栈顶元素
Status GetTop(SqStack S,SElemType &e)
{// 若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR
if(S.top == S.base)
return ERROR;
e = *(S.top-1);//栈顶指针减1,将栈顶元素赋给e
return OK;
}
//遍历栈
Status StackTraverse(SqStack S)
{
SElemType *p;
if (!S.base)
exit(OVERFLOW);
if (S.top == S.base)
cout << "栈中没有元素" << endl;
p = S.top;
while (p > S.base)
{
p--;
cout << *p << " ";
}
return OK;
}
//销毁栈
Status DestroyStack(SqStack &S)
{
S.top = NULL;
S.stacksize = 0;
delete(S.base);
return OK;
}
//清空栈
Status ClearStack(SqStack &S)
{
S.top = S.base;
return OK;
}
//判断栈是否为空栈
Status StackEmpty(SqStack S)
{
if (S.top == S.base)
return ERROR;
else
return OK;
}
//求栈的长度
Status StackLength(SqStack S)
{
if (S.top == S.base)
return ERROR;
else
return (S.top - S.base);
}
int main(){
int l,j;
SqStack s;
SElemType e;
SElemType t;
int c=-1;
cout<<"1.建立一个空栈\n";
cout<<"2.执行入栈操作\n";
cout<<"3.栈的长度\n";
cout<<"4.遍历栈\n";
cout<<"5.元素的出栈\n";
cout<<"6.判断是否为空栈\n";
cout<<"7.清空栈\n";
cout<<"8.销毁栈\n";
cout<<"0.退出!\n";
while(c!=0){
cout<<"请选择:";
cin>>c;
switch(c){
case 1:
if(InitStack(s)==OK)
cout<<"成功建立栈"<<endl;
else
cout<<"栈建立失败"<<endl;
break;
case 2:
int n;
cout<<"请输入栈中元素的个数:";
cin>>n;
cout<<"进栈元素依次为:"<<endl;
if(InitStack(s)==OK)
{
for(j=1;j<=n;j++)
{
Push(s,j);
cout<<j<<" ";
}
}
cout<<endl;
break;
case 3:
l=StackLength(s);
cout<<"栈的长度为:"<<l;
cout<<endl;
break;
case 4:
StackTraverse(s);
cout<<endl;
break;
case 5:
cout<<"依次弹出的栈顶元素为:";
while(GetTop(s,e)==OK){
cout<<e<<" ";
Pop(s,t);
}
cout<<endl;
break;
case 6:
cout<<"本栈是否为空栈:";
if(StackEmpty(s)==ERROR)
cout<<"是"<<endl;
else
cout<<"否"<<endl;
break;
case 7:
ClearStack(s);
cout<<"栈中元素为:";
StackTraverse(s);
break;
case 8:
if(DestroyStack(s)==OK)
cout<<"销毁栈成功!";
else
cout<<"销毁失败";
break;
}
}
return 0;
}
顺序栈的九种基本操作
最新推荐文章于 2024-01-23 20:18:22 发布