栈是一种特殊的线性表。限定仅在表的一端进行插入和删除操作。
根据栈的逻辑结构图,栈这个容器很像一个装得严丝合缝的箱子,我们最先放进去的“对象”被压在了最下面,而最后放入的却在最上面。因此,在取出栈中的元素时,我们要遵从“先进后出”的原则。这样简单且古板的逻辑是我们计算机系统的基石。
PS:本文使用顺序表来实现栈容器的构建。
栈的大体声明如下。其中 MAX_SIZE 栈的最大容量需要自行定义。
template <class DataType> class SeqStack { public: SeqStack(); //构造函数 ~SeqStack(); //析构函数 void Push(DataType x); //压栈 DataType Pop(); //弹栈,出栈 DataType GetTop(); //得到栈顶元素 bool Empty(); //判断栈是否为空 void PrintStack(); //按“先进后出”的原则打印栈 private: DataType data[MAX_SIZE]; //栈的本质,一个数组 int top; //栈顶位置下标 };
栈的构造函数,栈空,顶部位置下表为-1.
template <class DataType> SeqStack<DataType>::SeqStack() { top = -1; }
析构函数,对于顺组表构造的栈,仅需要释放数组的指针即可。
template <class DataType> SeqStack<DataType>::~SeqStack() { delete data; }
压栈、入栈。
template <class DataType> void SeqStack<DataType>::Push(DataType x) { if (top == MAX_SIZE - 1) throw "溢出"; data[++top] = x; }
弹栈、出栈,并返回弹出的对象值。
template <class DataType> DataType SeqStack<DataType>::Pop() { DataType x; if (top == -1) throw "溢出"; x = data[top--]; return x; }
得到栈顶元素值,不弹出栈顶元素。
template <class DataType> DataType SeqStack<DataType>::GetTop() { if (top == -1) throw "溢出"; return data[top]; }
判断栈是否为空。
template <class DataType> bool SeqStack<DataType>::Empty() { if (top == -1) return true; else return false; }
栈的遍历,按“先进后出”的次序输出栈的内容。
template <class DataType> void SeqStack<DataType>::PrintStack() { if (top == -1) cout << "SeqStack empty!" << endl; else { cout << "SeqStack elements:" << endl; for (int i = 0; i <= top; i++) cout << "No." << i << " " << data[i] << endl; } }
至此,栈的大部分基本声明与定义就结束了。
下附完整代码,望诸君共勉。
#pragma once
using namespace std;
const int MAX_SIZE = 100;
template <class DataType>
class SeqStack {
public:
SeqStack(); //构造函数
~SeqStack(); //析构函数
void Push(DataType x); //压栈
DataType Pop(); //弹栈,出栈
DataType GetTop(); //得到栈顶元素
bool Empty(); //判断栈是否为空
void PrintStack(); //按“先进后出”的原则打印栈
private:
DataType data[MAX_SIZE]; //栈的本质,一个数组
int top; //栈顶位置下标
};
template <class DataType>
SeqStack<DataType>::SeqStack() {
cout << "这是构造函数" << endl;
top = -1;
}
template <class DataType>
SeqStack<DataType>::~SeqStack() {
cout << "这是析构函数" << endl;
delete data;
}
template <class DataType>
void SeqStack<DataType>::Push(DataType x) {
if (top == MAX_SIZE - 1) throw "溢出";
data[++top] = x;
}
template <class DataType>
DataType SeqStack<DataType>::Pop() {
DataType x;
if (top == -1) throw "溢出";
x = data[top--];
return x;
}
template <class DataType>
DataType SeqStack<DataType>::GetTop() {
if (top == -1) throw "溢出";
return data[top];
}
template <class DataType>
bool SeqStack<DataType>::Empty() {
if (top == -1)
return true;
else
return false;
}
template <class DataType>
void SeqStack<DataType>::PrintStack() {
if (top == -1)
cout << "SeqStack empty!" << endl;
else {
cout << "SeqStack elements:" << endl;
for (int i = 0; i <= top; i++)
cout << "No." << i << " " << data[i] << endl;
}
}