顺序栈的基本操作实现
顺序栈的基本操作实现
本题实现了顺序栈的初始化、批量入栈、批量出栈、取栈顶元素。 |
#include<iostream>
#define MAXSIZE 100
#define OVERFLOW -2
#define ERROR 1
#define OK 0
using namespace std;
typedef int SElemType;
typedef struct{
SElemType *base;
// 栈底指针
SElemType *top;
// 栈顶指针
int stacksize;
// 栈可用的最大容量
}SqStack;
//初始化:构造一个空栈
void InitStack(SqStack &S){
S.base=new SElemType[MAXSIZE];
if(S.base==NULL)
{
exit(OVERFLOW);
}
S.top=S.base;
S.stacksize=MAXSIZE;
cout<<"初始化成功!"<<endl;
}
//入栈 将元素e压入栈顶
int Push(SqStack &S,SElemType &e){
// 判断是否栈满
if(S.top-S.base==S.stacksize){
cout<<"栈满了!"<<endl;
return ERROR;
}
*(S.top++)=e;
return 1;
//元素压入栈顶,栈顶指针加一
}
//出栈 将栈顶元素赋值给e
int Pop(SqStack &S,SElemType e){
// 判断是否栈空
if(S.top==S.base){
return ERROR;
}
e=*S.top--;
return 1;
}
//取栈顶元素
int GetTop(SqStack S){
if(S.top!=NULL){
cout<< *(S.top-1)<<endl;
}
}
void PushToStack(SqStack &S)
{
// 批量入栈
int n;
SElemType e;
cout<<"请输入入栈元素个数"<<endl;
cin>>n;
for(int i=0;i<n;i++)
{
cout<<"请输入第"<<i+1<<"个元素的值:"<<endl;
cin>>e;
if(Push(S,e)!=0){
cout<<e<<"已入栈"<<endl;
}
else {cout<<"栈已满"<<endl;}
}
}
void PopToStack(SqStack &S)
{
// 批量出栈
int n;
SElemType e;
cout<<"请输入出栈元素个数"<<endl;
cin>>n;
for(int i=0;i<n;i++)
{
if(Pop(S,e)!=0){
cout<<e<<"已出栈"<<endl;
}
else {cout<<"栈已空"<<endl;}
}
}
int main(){
SqStack S;
SElemType e;
InitStack(S);
loop:cout<<"1、压入元素"<<endl;
cout<<"2、出栈"<<endl;
cout<<"3、取栈顶元素"<<endl;
cout<<"请输入您选择的序号"<<endl;
int n;
cin>>n;
switch(n){
case 1:{
PushToStack(S);
cout<<"退出请按1,输入其他数字返回上级清单"<<endl;
int p;
cin>>p;
if(p == 1){
return 0;
}
else{
goto loop;
}
break;
}
case 2:{
PopToStack(S);
cout<<"退出请按1,输入其他数字返回上级清单"<<endl;
int p;
cin>>p;
if(p == 1){
return 0;
}
else{
goto loop;
}
break;
}
case 3:{
GetTop(S);
cout<<"退出请按1,输入其他数字返回上级清单"<<endl;
int p;
cin>>p;
if(p == 1){
return 0;
}
else{
goto loop;
}
break;
}
}
return 0;
}
废话一下~~
为什么压入元素之后就崩溃了?
检查了老半天发现原来是入栈那个步骤时if语句判断我只打了一个等号 心塞TAT
后来我又加了几个函数进行入栈出栈操作 因为书上那种一次只能出入一个元素 效率很低 批量出入可以让程序更实用~