顺序栈相关操作实现
//栈的初始化操作
void InitStack(SqStack &S)
//进栈操作
bool Push(SqStack &S, char x);
//出栈操作 用e返回
bool Pop(SqStack &S, char &e);
//获取栈顶元素
bool GetTop(SqStack &S, char e);
//判断栈是否为空
bool IsEmpty(SqStack S);
下面展示一些 代码。
//此篇是顺序栈 : 需要注意的是 顺序栈的出栈入栈以及获取栈顶元素的代码有时不同
// 区别在于初始化时 将top的初始值设为0还是-1
// 相应的改变是先进行赋值还是先进行top的移位
#include<iostream>
using namespace std;
#define MAXSIZE 10
typedef struct SqStack{
char data[MAXSIZE];
int top;
}SqStack;
//栈的初始化操作
void InitStack(SqStack &S)
{
S.top = -1;
}
//进栈操作
bool Push(SqStack &S, char x){
if(S.top == MAXSIZE - 1){
return false;//栈满报错
}
S.top++;
S.data[S.top] = x;
return true;
}
//出栈操作 用e返回
bool Pop(SqStack &S, char &e){
if(S.top == -1){
return false;//空栈
}
e = S.data[S.top];
S.top--;
return true;
}
//获取栈顶元素
bool GetTop(SqStack &S, char e){
if(S.top == -1){
return false;//空栈
}
e = S.data[S.top];
return true;
}
//判断栈是否为空
bool IsEmpty(SqStack S){
if(S.top == -1){
cout<<"当前栈为空!"<<endl;
return true;
}
else{
cout<<"当前栈不为空!"<<endl;
return false;
}
}
int main(){
SqStack S;
InitStack(S);
Push(S, 'a');
Push(S, 'b');
Push(S, 'c');
Push(S, 'd');
Push(S, 'e');
char aa, bb, cc, dd;
cout<<"依次出栈结果为:\n";
Pop(S, aa);
cout<<aa<<" ";
Pop(S, bb);
cout<<bb<<" ";
Pop(S, cc);
cout<<cc<<" ";
Pop(S, dd);
cout<<dd<<" ";
cout<<endl;
cout<<"当前栈是否为空?"<<endl;
IsEmpty(S);
cout<<endl;
for(int i = 0; i < 5; i++){
cout<<S.data[i];
}
return 0;
}