代码:
#include <iostream>
using namespace std;
void hanoi(int n, char x, char y, char z);
void move(char str1, char str2);
int main() {
for (int i = 0; ; i++) {
int n;
cout << "请输入n的值:" << endl;
cin >> n;
if (n == 0) {
cout << "end!" << endl;
break;
}
hanoi(n, 'A', 'B', 'C');
}
return 0;
}
void hanoi(int n, char x, char y, char z) {
if (n == 1)
move(x, z);
else {
hanoi(n - 1, x, z, y);
move(x, z);
hanoi(n - 1, y, x, z);
}
}
void move(char str1, char str2) {
static int i = 1;
cout << i++ << ':' << str1 << "->" << str2 << endl;
}
运行:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/05a46361f9804c52deef0629b1ef1f6f.png)