首页 > 解决方案 > “顶部”值不会改变我推送或弹出堆栈的次数

问题描述

我正在使用动态数组实现堆栈。我的想法很简单:我希望用户输入他/她想要的长度,然后创建一个具有该长度的堆栈。然后他/她可以push,pop一个整数;查看最大值和最大值(用于调试目的);检查它是满还是空(也用于调试)。他/她可以推直到堆栈已满然后必须弹出,他/她可以弹出直到它为空然后必须推。我使用 do while 和 switch 使其更容易调试和操作。但是当我开始测试时,我的 Stack 类的顶级属性仍然为 0,我推送或弹出了多少次。我一直在试图找到错误,但仍然没有找到。

这是我的代码:

#include <cstdio>
#include <iostream>

using std::cin;
using std::cout;
using std::endl;

class Stack {
    int top;
    int max; // max index
    int *data;
    public:
        Stack(int length);
        int isEmpty();
        int isFull();
        int push(int n);
        int pop();
        int getTop(void);
        int getMax(void);
        ~Stack(void);
};

Stack::Stack(int length){
    top = 0;
    max = length;
    data = new int[length+1];
}
int Stack::isEmpty(void){
    return top==0;
}
int Stack::isFull(void){
    return top==max;
}
int Stack::push(int n){
    if(!isFull()){
    data[++top] = n;
    return 1;
    }
    else return 0;

}
int Stack::pop(void){
    if(!isEmpty()){
        return data[top--];
    }
    else return -911; //rare and indicative number
}
int Stack::getTop(void){
    return top;
}
int Stack::getMax(void){
    return max;
}
Stack::~Stack(void){
    delete[] data;
}

int main(void){
    int length = 0;
    cout << "Enter stack's length': "; cin >> length;
    Stack list(length);
    char lock;
    do{
        cout << "1. push" << endl;
        cout << "2. pop" << endl;
        cout << "3. show top index" << endl;
        cout << "4. show max index" << endl;
        cout << "5. isFull?" << endl;
        cout << "6. isEmpty?" << endl;
        cout << "0. Quit" << endl;
        scanf("%d", &lock);
        switch(lock){
            case 1:
                int temp;
                cout << "Enter an integer: ";
                cin >> temp;
                printf(list.push(temp)?"success\n":"fail\n");
                break;
            case 2:
                cout << "Top's data: " << list.pop() << endl;
                break;
            case 3:
                cout << list.getTop() << endl;
                break;
            case 4:
                cout << list.getMax() << endl;
                break;
            case 5:
                printf(list.isFull()?"True\n":"False\n");
                break;
            case 6:
                printf(list.isEmpty()?"True\n":"False\n");
                break;
            case 0: break;
            default:
                cout << "Not an available work!" << endl;
        }
    } while (lock!= 0);

    return 0;
}

标签: c++stack

解决方案


你有微妙的内存损坏。原因:

q58036810.cpp:71:21: warning: format specifies type 'int *' but the argument has type 'char *' [-Wformat]
        scanf("%d", &lock);
               ~~   ^~~~~
               %s

当您在菜单上输入数字时,它太大了lock,因此覆盖了存储toplist. 更改char lockint lock,问题应该消失。将来,请始终编译并注意警告。此外,由于这个问题的性质,它不会始终如一地重现(即,它似乎在我的机器上运行良好。)


推荐阅读