【发布时间】:2014-02-17 18:47:49
【问题描述】:
这是堆栈上的 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 个堆栈来解决问题,并更好地了解您的代码在做什么。
-
一些一般性的建议:将你的输入逻辑与你的push/initialize/等分开,检查
top==-1before数组访问,你应该有一个初始化东西的构造函数. -
在这里“top--; return p;”您应该首先保存您想要返回的内容,然后减少 - 根据您的推送。但请先阅读上述建议。
-
我单步执行了代码,很快( /dev/pts/2
-
我忘了给 kudo 的 - 代码编译,它运行,你有一个简单的逻辑错误......但你可以尝试在你的命令循环中输入 quit。哎呀。