【实现类】
const int maxSize=100;
template <class T>
class seqStack{
public:
seqStack();
~seqStack();
void push(T x);//入栈
T pop();//出栈
T getTop();//获取栈顶元素
bool empty();//判断是否为空
private:
T data[maxSize];//数据域
int top;//栈首指针
}
【构造函数】
将栈首指针设为 -1 即可
template <class T>
seqStack<T>::seqStack(){
top=-1;
}
【进栈】
- 若 top>=maxSize,则给出上溢信息
- 栈指针加 1,指向进栈地址
- 新元素 x 进栈
template <class T>
void seqStack<T>::push(T x){
if(top==maxSize-1)//判断是否溢出
throw "上溢";
top++;//栈顶指针+1
data[top]=x;//新元素入栈
}
【出栈算法】
- 若 top<=0,则给出下溢信息
- 获取要退栈的元素 x
- 栈指针减1,指向栈顶
- 返回退栈元素
template <class T>
T seqStack<T>::pop(){
if(top==-1)//溢出判断
throw "下溢";
T x=data[top];//取出栈元素
top--;//栈顶指针-1
return x;//返回出栈元素
}
【判断栈空】
判断栈顶指针是否为 -1,若 top=-1,则栈空
template <class T>
bool seqStack<T>::empty(){
if(top==-1)
return true;
return false;
}
【取栈顶元素】
- 判断栈是否为空
- 若栈不为空,直接返回栈顶元素 data[top]
template <class T>
T seqStack<T>::getTop(){
if(empty())
throw "栈为空";
return data[top];
}