#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
#define ms(a) memset(a,0,sizeof(a))
#define N 100
typedef int Elementtype;
//栈的结构体
struct node{
int Topofstack=-1;
Elementtype Array[N];
};
typedef node STACK;
//创建栈
STACK CreateStack(){
STACK S;
return S;
}
//判断栈是否为空,是返回1
int IsEmpty(STACK S){
return S.Topofstack==-1;
}
//将栈置空
void MakeEmpty(STACK &S){
S.Topofstack=-1;
}
//进栈
void Push(Elementtype x,STACK &S){
if(S.Topofstack>=N-1)
return;
S.Array[++S.Topofstack]=x;
}
//出栈
void Pop(STACK &S){
if(IsEmpty(S)){
cout<<"The stack is empty."<<endl;
return;
}
S.Topofstack--;
}
//返回栈顶元素
Elementtype Top(STACK S){
if(IsEmpty(S)){
cout<<"The stack is empty."<<endl;
}
else{
return S.Array[S.Topofstack];
}
}
//打印栈中元素,从栈顶开始打印
void Print(STACK S){
int tem=S.Topofstack;
if(IsEmpty(S)){
cout<<"The stack is empty."<<endl;
}
else{
while(tem!=-1){
cout<<S.Array[tem--]<<" ";
}
cout<<endl;
}
}
int main(){
STACK S=CreateStack();
Push(1,S);
Push(2,S);
Push(3,S);
Push(4,S);
Push(5,S);
Print(S);
Pop(S);
cout<<Top(S)<<endl;
Pop(S);
Print(S);
return 0;
}
栈——数组实现
最新推荐文章于 2022-03-29 16:57:58 发布