pop()无法正常工作

时间:2014-02-17 18:47:49

标签: c++ class

这是堆栈上的c ++代码。请注意这里的额外代码

#include<iostream>
using namespace std;
class mystack
{
    private:
        int top;
        int size;
        int * s;
    public:
        void initialize()
        {
            top=-1;
            cin>>size;
            s=new int[size];
        }   
        ~mystack(){delete [] s;}
        void push()
        {
            int x;
            if(top==size-1)
                cout<<"stack overflow!"<<endl;
            else
            {
                cout<<"Enter element to be pushed:";
                cin>>x;
                top++;
                s[top]=x;
                cout<<s[top]<<endl;
            }
        }   
        int pop()
        {
            int p=s[top];
            if(top==-1)
                return 0;
            else
            {
                top--;
                return p;
            }
        }
        int maxsize()
        {
            return size;
        }
        int isempty()
        {
            if(top==-1)
                return 0;
            else
                return 1;
        }
        void display()
        {
            int i,p=top;
            cout<<s[0]<<endl;
            for(i=0;i<=p;i++)
                cout<<s[i]<<endl;
        }
};
int main()
{
    int n,i;
    cout<<"Enter no. of stacks:";
    cin>>n;
    mystack * st=new mystack[n];
    for(i=0;i<n;i++)
    {
        cout<<"Enter size of stack "<<i+1<<":";
        st[i].initialize();
    }
    int c,s;
    while(1)
    {
        cout<<"*****Operations*****"<<endl;
        cout<<"1.Push 2.Pop 3.Maxsize 4.isempty 5.Display 6.Quit"<<endl;
        cout<<"Enter your choice:";
        cin>>c;
        if(n>1)
        {
            cout<<"Operation on which stack:";
            cin>>s;
        }
        else
            s=1;
        if(c==1)
            st[s-1].push();
        else if(c==2)
        {
            if(st[s-1].pop()==0)
                cout<<"stack underflow!"<<endl;
            else
                cout<<st[s-1].pop()<<endl;
        }
        else if(c==3)
            cout<<st[s-1].maxsize()<<endl;
        else if(c==4)
        {
            if(st[s-1].isempty()==0)
                cout<<"True"<<endl;
            else
                cout<<"False"<<endl;
        }
        else if(c==5)
            st[s-1].display();
        else if(c==6)
            break;
        else
        {
            cout<<"Wrong input!"<<endl;
            continue;
        }
    }   
    return 0;
}

这里访问pop操作给出了top-1的元素。我无法理解为什么。我该怎么办?当我返回s [top--]同样的事情正在发生。

1 个答案:

答案 0 :(得分:0)

由于你还没有回到这一点,我将假设你已经发现了你的逻辑错误。

所以这是我发现的一个错误。可能会有更多,我放弃了......

在下面的代码中,pop()被调用了多少次?

  else if(c==2)
    {
        if(st[s-1].pop()==0)
            cout<<"stack underflow!"<<endl;
        else
            cout<<st[s-1].pop()<<endl;
    }