我最近在学习数据结构,记录一些学习中编写的代码,方便数据结构的初学者。
#include <iostream>
#define Maxsize 10
using namespace std;
typedef struct{
int data[Maxsize];
int top;
} SqStack;
//初始化栈
void InitStack(SqStack &S){
S.top = -1;
}
//判断栈是否为空
bool StackEmpty(SqStack S){
if(S.top == -1){
return true;
} else {
return false;
}
}
//进栈
bool Push(SqStack &S, int num){
if(S.top == Maxsize-1){
return false;
} else {
S.data[++S.top] = num;
return true;
}
}
//读取栈顶元素
bool GetTop(SqStack S, int &num){
if(S.top == -1){
return false;
} else {
num = S.data[S.top];
cout << "栈顶元素为:" << num << endl;
return true;
}
}
//出栈
bool Rop(SqStack &S, int num){
if(S.top == -1){
return false;
} else {
num = S.data[S.top--];
cout << "被出栈元素为:"<< num << endl;
return true;
}
}
int main(){
int num;
SqStack S;
//初始化栈
InitStack(S);
//判断栈是否为空
bool empty = StackEmpty(S);
std::cout << std::boolalpha;
std::cout << "栈为空? " << empty << std::endl;
//进栈
cout << "输入要入栈的元素:" << endl;
cin >> num;
Push(S, num);
//读取栈顶元素
GetTop(S, num);
//出栈
Rop(S, num);
}
如果我的代码对你有帮助,记得点赞+收藏哦!