C++的顺序栈和链栈
栈 LIFO
限定仅在一端进行插入和删除操作的线性表
栈的操作特性:后进先出(Last In First Out,LIFO)
顺序栈
#include<iostream>
using namespace std;
const int StackSize = 10;
template <typename DataType>
class SeqStack
{
public:
SeqStack();
~SeqStack(){
};
void Push( DataType x ); // 入栈
DataType Pop( ); // 出栈
DataType GetTop( ); // 取栈顶元素
int Empty( ); // 判空
void PrintStack(); // 遍历栈,从顶到下
private:
DataType data[StackSize];
int top;
};
// 初始化一个空的顺序栈
template <typename DataType>
SeqStack<DataType> :: SeqStack()
{
top = -1;
}
// 入栈,栈满:top=StackSize-1
template <typename DataType>
void SeqStack<DataType> :: Push(DataType x)
{
if (top == StackSize - 1) throw "上溢";
data[++top] = x;
}
// 出栈,栈空:top=-1
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>
int SeqStack<DataType>