数据结构--顺序栈C++(模板类实现)
作者:
AmbitionX
,
2022-05-02 15:02:22
,
所有人可见
,
阅读 170
#include <iostream>
using namespace std;
const int StackSize = 10;
template <typename DataType>
class SeqStack
{
public:
SeqStack();
// ~SeqStack(); // 销毁栈 由于栈是静态存储的 所以函数为空
void Push(DataType x); // 入栈操作,将x元素入栈
DataType Pop(); // 出栈操作,将栈顶元素弹出
DataType GetTop(); // 取出栈顶元素
void Empty(); // 判断栈是否为空
private:
DataType data[StackSize]; // 存放栈元素的数组
int top; // 栈顶元素在数组中的下标
};
// 初始化
template <typename DataType>
SeqStack<DataType>:: SeqStack()
{
top = -1;
}
// 销毁栈 静态存储 故函数结束自会释放
// template <typename DataType>
// SeqStack<DataType>:: ~SeqStack()
// {
// }
// 入栈操作,将x元素入栈
template <typename DataType>
void SeqStack<DataType>:: Push(DataType x)
{
if (top == StackSize - 1) throw "上溢";
data[++ top] = x;
}
// 出栈操作,将栈顶元素弹出
template <typename DataType>
DataType SeqStack<DataType>:: Pop()
{
DataType x;
if (top == -1) throw "下溢";
x = data[top --];
return x;
}
// 取出栈顶元素
template <typename DataType>
DataType SeqStack<DataType>:: GetTop()
{
return data[top];
}
// 判断栈是否为空
template <typename DataType>
void SeqStack<DataType>:: Empty()
{
if (top == -1) cout << "为空" << endl;
else cout << "不空" << endl;
}
int main()
{
SeqStack<int> S; // 定义栈
cout << "1 和 2 入栈";
S.Push(1);
S.Push(2);
cout << "当前栈顶元素位: " << S.GetTop() << endl;
int x;
try
{
x = S.Pop(); // 出栈
cout << "出栈操作,出来的元素是: " << x << endl;
}
catch (char *str)
{
cout << str << endl;
}
int y;
try
{
cout << "请输入待入栈元素: ";
cin >> y;
cout << "待入栈元素为: " << y << endl;
S.Push(y); // 进栈
}
catch (char *str)
{
cout << str << endl;
}
S.Empty();
return 0;
}