stack_size和stack_top函数可以参考其他三个函数实现,栈顶指针指向栈顶元素的下一位置。
#define maxsize 100
class mystack
{
public:
mystack(int len1=0, int len2=maxsize):top1(len1),top2(len2)
{
arr = new int[maxsize];
}
~mystack(){delete []arr;}
bool stack_full();
void stack_push(int index, int data);
void stack_pop(int index);
private:
int *arr;
int top1;
int top2;
};
bool mystack::stack_full()
{
if(top1==top2) return true;
else return false;
}
void mystack::stack_push(int index, int data)
{
if(index==1){
if(top1<top2){
arr[top1] = data;
top1++;
}
else{
cout << "stack is full..." << endl;
}
}
else if(index==2){
if(top1<top2){
arr[top2] = data;
top2--;
}
else{
cout << "stack is full..." << endl;
}
}
else
cout << "first parameter is invalid..." << endl;
}
void mystack::stack_pop(int index)
{
if(index==1){
if(top1>0)
top1--;
else
cout << "stack 1 is empty..." << endl;
}
else if(index==2){
if(top2<maxsize-1)
top2++;
else
cout << "stack 2 is empty..." << endl;
}
else
cout << "first parameter is invalid..." << endl;
}
参考资料: