两栈共享空间的顺序栈C++实现

来源:互联网 发布:加油站经营软件 编辑:程序博客网 时间:2024/04/30 14:15

程序中如果需要同时使用具有相同数据类型的两个栈的时候,可以采用一个数组,让一个栈的栈底在该数组的起始端,另一个栈的栈底在数组的结尾,有利于节省空间。

/*************************************************************************    > File Name: BothStack.cpp    > Author: Shorey    > Mail: shoreybupt@gmail.com    > Created Time: 2015年03月22日 星期日 09时49分06秒 ************************************************************************/#include<iostream>using namespace std;#define StackSize 100class BothStack{public:BothStack(){              //构造函数top1=-1;top2=StackSize;}~BothStack(){;}           //析构函数void Push(int i,int x);//将x元素压入栈iint Pop(int i);          //对栈i进行出栈操作int GetTop(int i);       //取栈i的栈顶bool Empty(int i);       //判断栈是否为空private:int data[StackSize];int top1,top2;};void BothStack::Push(int i,int x){if(top1==top2-1){cout<<"stack is full!"<<endl;return ;}if(i==1)data[++top1]=x;if(i==2)data[--top2]=x;}int BothStack::Pop(int i){if(i==1){if(top1==-1){cout<<"stack is empty"<<endl;}elsereturn data[top1--];}if(i==2){if(top2==StackSize){cout<<"stack is empty"<<endl;}elsereturn data[top2++];}}int BothStack::GetTop(int i){if(i==1){if(top1==-1){cout<<"stack is empty"<<endl;}elsereturn data[top1];}if(i==2){if(top2==StackSize){cout<<"stack is empty"<<endl;}elsereturn data[top2];}}bool BothStack::Empty(int i){if(i==1){if(top1==-1)return true;else        return false;}if(i==2){if(top2==StackSize)return true;else               return false;}}int main(){BothStack s;    s.Push(1,4);s.Push(1,5);s.Push(2,8);s.Push(2,9);    cout<<s.GetTop(1)<<endl;cout<<s.GetTop(2)<<endl;return 0;}


1 0
原创粉丝点击