堆栈的顺序表示ADT_SeqStack
最后更新于:2022-04-01 20:51:15
栈的实现,包含的函数有Top(), Push(), Pop().
简单易懂的代码~
实现代码:
~~~
#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
using namespace std;
template
class Stack
{
public:
virtual bool IsEmpty() const = 0; // 判断栈是否为空 为空则返回true
virtual bool IsFull() const = 0; // 判断栈是否满 满则返回true
virtual bool Top(T &x) const = 0; // 返回栈顶元素 操作成功则返回true
virtual bool Push(T x) = 0; // 入栈 操作成功则返回true
virtual bool Pop() = 0; // 出栈 操作成功则返回true
virtual void Clear() = 0; // 清除栈中所有元素
/* data */
};
template
class SeqStack: public Stack
{
public:
SeqStack(int mSize);
~SeqStack() { delete []s; }
bool IsEmpty() const { return top == 1; }
bool IsFull() const { return top == maxTop; }
bool Top(T &x) const;
bool Push(T x);
bool Pop();
void Clear() { top = -1; }
/* data */
private:
int top, maxTop; // 栈顶指针 最大栈顶指针
T *s;
};
template
SeqStack::SeqStack(int mSize)
{
maxTop = mSize - 1;
s = new T[mSize];
top = 1;
}
template
bool SeqStack::Top(T &x) const
{
if(IsEmpty()) {
cout << "Stack is empty" << endl;
return false;
}
x = s[top];
return true;
}
template
bool SeqStack::Push(T x)
{
if(IsFull()) {
cout << "Stack is full" << endl;
return false;
}
s[++top] = x;
return true;
}
template
bool SeqStack::Pop()
{
if(IsEmpty()) {
cout << "Stack is empty" << endl;
return false;
}
top--;
return true;
}
int main(int argc, char const *argv[])
{
SeqStack s(5);
for(int i = 0; i < 3; ++i)
s.Push(i); // s包含0 1 2
int x;
if(s.Top(x)) cout << "The top of s is " << x << endl;
if(s.Push(x)) cout << "Push successfully" << endl;
if(s.Pop()) cout << "Pop successfully" << endl;
s.Clear();
return 0;
}
~~~
';