//以下代码生成访问冲突或分段错误 //我正在寻找河内塔的简单解决方案,我应该自己写 //请注明以下代码漏洞,而不是给你的精英代码:)河内递归塔,访问冲突/分段错误,在dev C++编译器上
//使用三个栈
#include <iostream>
using namespace std;
#define max 50
typedef struct stack{ //union?
int tos;
int els[max]; //stack->els[1] = tos
}stack; //template stack?
void toh(int, stack * , stack *, stack *);
void display(stack *);
int main(){
cout<<"Enter the number of discs (<=50) in Tower of Hanoi\n";
int n;
cin>>n;
stack *A,*B,*C;
toh(n, A,B,C);
system("pause");
return 0;
}
void toh(int n, stack *A, stack *B, stack *C){
if (n == 1) {
int temp = A->els[A->tos]; //switch case i=1,2,3 tos[i]
A->tos -= 1; //OR stack * A, A->tos?
C->tos += 1;
C->els[C->tos] = temp;
// push the popped item in stack C
cout<<"A\t";
display(A);
cout<<"\nB\t";
display(B);
cout<<"\nC\t";
display(C);
}
else {
toh(n-1, A, C, B);
toh(1, A, B, C);
toh(n-1, B, A, C);
}
}
void display(stack * X){ //and not int[] stack
cout<<"The stack elements are :\n";
for(int i = 1; i <= X->tos; i++){//impo to start with 1 if tos = 0 init
cout<<X->els[i];
cout<<"\t";
}
}
什么是在进入'toh'递归A,B,C的值,在你看来? – 2013-03-18 18:41:41
Steve向你暗示,你的程序永远不会创建一个'stack'。 – 2013-03-18 18:50:00
输入no后,运行时异常很快发生。在我的情况下,光盘的数量是3,程序只是挂起.A,B,C是作为堆栈实现的塔,A应该包含3个光盘,如3,2,1从下到上(如果我们假设3> 2> 1代表较大盘>中等>更小),对于B和C,它们每个都有3个NULL值。 – user1776433 2013-03-18 18:52:09