c++數據結構 共享棧的實現

#include<iostream>
using namespace std;
const int stacksize=100;

class bothstack 
{
    public:
        bothstack(){top1=-1;top2=stacksize;}
        ~bothstack(){}
        void push(int i,int x);
        void pop(int i);
        void gettop(int i);
        void empty(int i);
    private:
        int data[stacksize];
        int top1,top2;
};

void bothstack::push(int i,int x)
{
    if(top1==top2-1)throw"上溢";
    if(i==1)data[++top1]=x;
    if(i==2)data[--top2]=x;
}

void bothstack::pop(int i)
{
    if(i==1)
    {
        while(top1!=-1)
        cout<<data[top1--]<<" ";
        cout<<endl;
    }
    if(i==2)
    {
        while(top2!=stacksize)
        cout<<data[top2++]<<" "; 
        cout<<endl;
    }
}

void bothstack::gettop(int i)
{
    if(i==1)
    {
        if(top1!=-1) 
        cout<<data[top1]<<endl;
        else
        cout<<"stack empty"<<endl;
    }
    if(i==2)
    {
        if(top2!=stacksize)
        cout<<data[top2]<<endl;
        else
        cout<<"stack empty"<<endl;
    }
}
void bothstack::empty(int i)
{
    if(i==1)
    {
        if(top1==-1)
        cout<<"stack empty"<<endl;
        else 
        cout<<"stack is not empty"<<endl;
    }
    if(i==2)
    {
        if(top2==stacksize)
        cout<<"stack empty"<<endl;
        else 
        cout<<"stack is not empty"<<endl;
    }
}
int main()
{
    int i,j;
    cin>>i>>j;
    bothstack b;
    b.empty(i);
    b.empty(j); 
    b.push(i,10);
    b.push(i,15); 
    b.push(j,2);
    b.push(j,1);
    b.gettop(i);
    b.gettop(j);
    b.pop(i);
    b.pop(j);
    b.gettop(i);
    b.gettop(j);
    cout<<endl;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章