今天给大家分享一下C++数据结构之中顺序栈的实现
首先对栈的操作比较简单,借助栈顶指针S.top实现初始化、判空、出栈、入栈等操作:
#define MaxSize 50
typedef int Elem;
typedef struct {
Elem data[MaxSize];
int top;
}SqStack;
//初始化
void InitStack(SqStack& S)
{
S.top = -1;
}
//判栈空
bool IsEmpty(SqStack S)
{
if (-1 == S.top)
{
return true;
}
else
{
return false;
}
}
//进栈
bool Pop(SqStack& S, Elem x)
{
if (MaxSize - 1 == S.top)
{
return false;
}
S.data[++S.top] = x;
return true;
}
//出栈
bool Push(SqStack& S, Elem& x)
{
if (-1 == S.top)
{
return false;
}
x = S.data[S.top--];
return true;
}
//读取栈顶元素
bool GetStack(SqStack S, Elem& x)
{
if (-1 == S.top)
{
return false;
}
x = S.data[S.top];
return true;
}
下面附上流程图帮助读者理解记忆,你也可以对照着流程图自己把代码实现一遍。