【问题标题】:Stack showing overflow output but the tutorial shows otherwise [closed]堆栈显示溢出输出,但教程显示其他 [关闭]
【发布时间】:2021-07-23 01:56:39
【问题描述】:

我使用教程编写了这段代码。他的输出是正确的,但我得到了 stackoverflow 和内存地址作为输出,虽然我的代码和他的完全一样。我已经声明了数组大小 100,但它仍然不起作用

#include<iostream>
using namespace std;

#define n 100
class stack{
    int* arr;
    int top;

    public:
    stack(){
        arr=new int[n];
        top=-1;
    };
    void push(int x){
        if(top=n-1){
            cout<<"Stack overflow"<<endl;
            return;

        }
        top++;
        arr[top]=x;
    };
    void pop(){
        if(top==-1){
            cout<<"No element to pop"<<endl;
            return;
        }
        top--;
    };
    int Top(){
        if(top==-1){
            cout<<"Stack is empty"<<endl;
            return -1;
        }
        return arr[top];
    };
    bool empty(){
        return top==-1;
    }

};
int main(){
    stack st;
    st.push(1);
    st.push(2);
    st.push(3);
    cout<<st.Top()<<endl;
    st.pop();
    cout<<st.Top()<<endl;
    st.pop();
    st.pop();
    st.pop();
    cout<<st.empty()<<endl;

   
   
   
    return 0;

}

【问题讨论】:

  • 这看起来像是一个完美的调试器练习。
  • 或调整编译器的练习,我无法编译此代码:godbolt.org/z/Krx1fnGPW
  • 无意冒犯,但几乎每次有人说“完全一样”时,它不是;)

标签: c++ data-structures stack


【解决方案1】:

我已经运行了代码并且清楚地看到在你的“推”方法“if”条件下你又错过了一个“=”,而且我已经修改了你的代码来帮助你。希望对您有所帮助。

我做了一些小更新:

  1. "inserted {integer}" - 在推送方法中添加了消息。
  2. 弹出时显示顶部元素 1.
#include<iostream>
using namespace std;

#define n 100
class stack{
    int* arr;
    int top;

    public:
    stack(){
        arr=new int[n];
        top=-1;
    };
    void push(int x){
        if(top==n-1){
            cout<<"Stack overflow"<<endl;
            return;

        }
        top++;
        arr[top]=x;
        cout<<"inserted "<<arr[top]<<endl;
    };
    void pop(){
        if(top==-1){
            cout<<"No element to pop"<<endl;
            return;
        }
        top--;
    };
    int Top(){
        if(top==-1){
            cout<<"Stack is empty"<<endl;
            return -1;
        }
        return arr[top];
    };
    bool empty(){
        return top==-1;
    }
};
int main(){
    stack st;
    st.push(1);
    st.push(2);
    st.push(3);
    cout<<st.Top()<<endl; // 3
    st.pop(); // pops 3
    cout<<st.Top()<<endl; // 2
    st.pop(); // pops 2
    cout<<st.Top()<<endl; // 1
    st.pop(); // pops 1
    st.pop(); // stack underflow
    cout<<st.empty()<<endl;
    return 0;
}

【讨论】:

  • if(top=n-1) 中的作业找到了很好的发现 - 如果您也指出您更改的其他内容(以及原因),那也很好。
  • 现在你可以查看@TedLyngmo
  • @Usama 如果这解决了问题,请考虑accepting 的答案。
  • @iam_anirban 我已经给你投了赞成票,但我认为现在好多了。
  • 谢谢@TedLyngmo
猜你喜欢
  • 1970-01-01
  • 2013-06-06
  • 1970-01-01
  • 2012-06-02
  • 1970-01-01
  • 2022-12-10
  • 1970-01-01
  • 2022-10-15
  • 2011-07-30
相关资源
最近更新 更多