先贴代码。
//栈的顺序实现
#define MaxSize 100
typedef struct
{
int Data[MaxSize];
int top;
}Myst;
class test003
{
public:
void initiST(Myst& S)
{
S.top = -1;
}
public:
bool pushST(Myst& S, int val)
{
if (S.top == MaxSize - 1)
{
cout << "栈已满,无法继续插入元素" << endl;
return false;
}
S.top += 1;
S.Data[S.top] = val;
return true;
}
bool popST(Myst& S ,int &X)
{
if (S.top == -1)
{
cout << "栈为空,无法进行出栈操作" << endl;
return false;
}
X = S.Data[S.top];
S.top -= -1;
return true;
}
bool topST(Myst S, int& X)
{
if (S.top == -1)
{
cout << "栈为空,无法返回栈顶元素" << endl;
return false;
}
X = S.Data[S.top];
return true;
}
bool sizeST(Myst S, int& X)
{
if (S.top == -1)
{
cout << "栈为空,长度为零" << endl;
return false;
}
X = S.top + 1;
return true;
}
bool emptyST(Myst S)
{
if (S.top == -1)
{
return true;
}
return false;
}
vector<int> printST(Myst S)
{
vector<int> ve;
int temp = S.top;
while(temp-->-1)
{
ve.push_back(S.Data[temp]);
}
if (temp == -1)
{
return ve;
}
}
};
以上代码用一块固定且连续的内存来模拟实现了栈的功能,包括初始化、进栈、出栈、返回栈顶元素、返回栈内元素个数、是否栈空、遍历输出栈内元素等功能。
在初始化、进栈、出栈中形参是Myst类的引用,这是因为以上函数需要对栈做出修改。而出栈、返回栈顶元素、返回栈内元素个数等函数内有一个int类的引用,同样出于以上目的。