首页 > 编程 > C++ > 正文

C++ 实现汉诺塔的实例详解

2020-01-26 13:57:08
字体:
来源:转载
供稿:网友

C++ 实现汉诺塔的实例详解

前言:

有A,B,C三塔,N个盘(从小到大编号为1-N)起初都在A塔,现要将N个盘全部移动到C塔(按照河内塔规则),求最少移动次数以及每次的移动详细情况。

要求:

需要采用递归方法和消除尾递归两种方法编写。

盘数N由用户从标准输入读入,以一个整数表示,然后请调用两个方法按照下面例子所述分别在屏幕中输出结果(正常情况下一个输入数据会显示同样的输出结果2次)。

实现代码:

#include<iostream>using namespace std;void move(int count,char start='a',char finish='b',char temp='c'){ if(count>0) {  move(count-1,start,temp,finish); cout<<"Move "<<count<<" from "<<start<<" to "<<finish<<endl; move(count-1,temp,finish,start); }}void move_without_recursion(int count,char start='a',char finish='b',char temp='c'){ char swap; while(count>0) {  move_without_recursion(count-1,start,temp,finish); cout<<"Move "<<count<<" from "<<start<<" to "<<finish<<endl; count--; swap=start; start=temp; temp=swap; }}int main(){ int count; cout<<"please enter the number:"; cin>>count; cout<<"递归方法运行过程:"<<endl;  move(count);  cout<<"消除尾递归方法运行过程:"<<endl;  move_without_recursion(count);return 0;}

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表