hanoi的c++塔:程序有时在没有完成塔的情况下终止



我试图使用堆栈实现hanoi之塔,但在运行程序时似乎出现了一些问题。它有时运行良好,但有时程序会终止。我创建了一个单独的类作为堆栈。

class stack{
int* arr;
int stackSize;
public:
stack(int size = 0);
~stack();
void push(int a);
int pop();
};
stack::stack(int size){
this->arr = new int(size);
this->stackSize = 0;
}
stack::~stack(){
delete []this->arr;
}
void stack::push(int a){
this->stackSize++;
int* temp = new int(this->stackSize);
for(int i = 0; i < this->stackSize; i++){
temp[i] = this->arr[i];
}
temp[this->stackSize-1] = a;
delete []this->arr;
this->arr = temp;
}
int stack::pop(){
if(this->stackSize <= 0){
cout << "stack underflow" << endl;
}else{
this->stackSize--;
int popped = this->arr[this->stackSize];
int* temp = new int(this->stackSize);
for(int i = 0; i < this->stackSize; i++)    {
temp[i] = this->arr[i];
}
delete []this->arr;
this->arr = temp;
return popped;
}
}
void toh(int n, stack &s, stack &des, stack &aux){
if (n <= 0)
return;
toh(n-1, s, aux, des);
des.push(s.pop());
display();
toh(n-1, aux, des, s);
}

this->arr = new int(size);不为数组分配内存,而是为单个整数分配内存。如果你想要this->arr = new int[size];,你也可以在推送功能中做类似的事情。

此外,添加时,您的推送应该只在数组已满时分配一个新数组。

此外,在pop中,如果if为true,则不会返回值。应该引发异常,或者返回一个伪值。

相关内容

最新更新