"top"值不会改变我推送或弹出堆栈的次数

"top" value won't change how many times ever i push or pop a stack

本文关键字:堆栈 top 改变      更新时间:2023-10-16

我正在使用动态数组实现堆栈。我的想法很简单:我希望用户输入他/她想要的长度,然后创建一个具有该长度的堆栈。然后他/她可以推,弹出一个整数;查看最大值和最大值(用于调试目的(;检查它是满的还是空的(也用于调试(。他/她可以推到堆栈满然后必须弹出,他/她可以弹出直到它空然后必须推。我使用 do while 和切换以使其更容易调试和操作。 但是当我开始测试时,我的 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)?"successn":"failn");
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()?"Truen":"Falsen");
break;
case 6:
printf(list.isEmpty()?"Truen":"Falsen");
break;
case 0: break;
default:
cout << "Not an available work!" << endl;
}
} while (lock!= 0);
return 0;
}

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

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

当您在菜单上输入数字时,它太大而无法lock因此覆盖了top存储在list中的内存。将char lock更改为int lock,问题应该会消失。将来,请始终使用警告进行编译并注意它们。此外,由于这个问题的性质,它不会始终如一地重现(即,它似乎在我的机器上工作正常。