【实现类】
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 号栈,栈指针设为存储空间头部,对于 2 号栈,栈指针设为存储空间尾部
template <class T>
bothStack<T>::bothStack(){
top1=-1;
top2=maxSize;
}
【进栈】
- 若 top1=top2-1 说明栈满,则给出上溢信息
- 若在栈 1 插入元素,则栈 1 指针加 1,新元素 x 进栈
- 若在栈 1 插入元素,则栈 2 指针减 1,新元素 x 进栈
template <class T>
void bothStack<T>::push(int i,T x){
if(top1==top2-1)//判断是否溢出
throw "上溢";
if(i==1){
top1++;//栈顶指针+1
data[top1]=x;//新元素入栈
}
if(i==2){
top2--;//栈顶指针-1
data[top2]=x;//新元素入栈
}
}
【出栈算法】
- 若在栈 1 删除,首先判断是否为空栈,若 top1=-1,则给出下溢信息,否则删除并返回栈 1 的栈首元素
- 若在栈 2 删除,首先判断是否为空栈,若 top2=-1,则给出下溢信息,否则删除并返回栈 2 的栈首元素
template <class T>
T bothStack<T>::pop(int i){
if(i==1){
if(top1==-1)//溢出判断
throw "栈1下溢";
T x=data[top1];//取出栈元素
top1--;//栈顶指针-1
return x;//返回出栈元素
}
if(i==2){
if(top1==-1)//溢出判断
throw "栈2下溢";
T x=data[top1];//取出栈元素
top1++;//栈顶指针+1
return x;//返回出栈元素
}
}
【判断栈空】
对于第 i 个栈,要判断其是否为空,只要判断其栈顶指针,若 top1=-1 或 top2=maxSize,则栈空
bool bothStack<T>::empty(int i){
if(i==1)
if(top1==-1)
return true;
if(i==2)
if(top2==maxSize)
return true;
return false;
}
【取栈顶元素】
- 判断要取元素的栈是否为空
- 若栈不为空,直接返回栈顶元素 data[top]
template <class T>
T bothStack<T>::getTop(int i){
if(i==1){
if(empty(1))
throw "栈为空";
return data[top1];
}
if(i==2){
if(empty(2))
throw "栈为空";
return data[top2];
}
}