ALin带你学习栈的基本操作
#include"stdafx.h"
#include<iostream>
using namespace std;
constexpr auto M = 5;
struct SeqStack {
int top;//用来记住栈顶
int S[M];//这里的栈的最大容量m是固定的,大家可以想想怎么改,才能创建一个自定义大小的栈?先自己动手,我会在下篇再带你做简单的修改
};
typedef struct SeqStack *PStack;
PStack InitiaStack() {//初始化
PStack p = (PStack)malloc(sizeof(struct SeqStack));
if (p!=NULL)
{
p->top = -1;
for (int i = 0; i < M; i++)
{
p->S[i] = 0;
}
return p;
}
else
{
free(p);
}
cout << "创建失败" << endl;
return NULL;
}
int Empty(PStack pstack) {//检查栈是否为空
return pstack-> top == -1;
}
int Full(PStack pstack) {//检查栈满
return pstack-> top == M - 1;
}
int GetTop(PStack pstack) {//获取栈顶
int item;
if (Empty(pstack))
{
cout << "空栈" << endl;
return 0;
}
else
{
item =pstack->S[pstack->top];
cout << "当前栈顶元素为" << item << endl;
return 1;
}
}
int Push(PStack pstack, int item) {
if (Full(pstack))
{
cout << "当前栈空间不足,请结束进栈操作" << endl;
return 0;
}
else
{
pstack->S[++pstack->top] = item;//进栈,修改栈顶
cout << "当前进栈元素为:" << item << endl;
return 1;
}
}
int Pop(PStack pstack) {
int item;
if (Empty(pstack))
{
return 0;
}
else
{
item = pstack->S[pstack->top--];
cout << item << "出栈成功" << endl;
return 1;
}
}
int main() {
PStack p=InitiaStack();
int item;
cout << "请输入进栈元素,以0结束" << endl;
while (true)
{
cin >> item;
if (item)
{
Push(p,item);
}
else
{
break;
}
}
Pop(p);
GetTop(p);
return 0;
}