//以下代码生成访问冲突或分段错误 //我正在寻找河内塔的简单解决方案,我应该自己写 //请指出下面代码中的缺陷,而不是提供您的精英代码 :)
//使用三个堆栈递归解决汉诺塔问题
#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";
}
}