//欢迎挑刺儿!!!
#include <iostream>
#include<stack>
using namespace std;
void hano(int n,char a='A',char b='B',char c='C');
int main()
{
int n;
cin>>n;
hano(n);
return 0;
}
void hano(int n,char a,char b,char c)
{
stack<int> st;
st.push(n);
st.push(a);
st.push(b);
st.push(c);
while (false==st.empty())
{
char _c=st.top();
st.pop();
char _b=st.top();
st.pop();
char _a=st.top();
st.pop();
char _n=st.top();
st.pop();
if(_n==1)
{
cout<<_a<<" --> "<<_c<<endl;
continue;
}
//栈为先进后出的数据,因而
//先将n-1个盘子由b通过a挪到c
st.push(_n-1);
st.push(_b);
st.push(_a);
st.push(_c);
//将最底下的盘子由a挪到c
st.push(1);
st.push(_a);
st.push(_b);
st.push(_c);
//将n-1个盘子由a通过c挪到b
st.push(_n-1);
st.push(_a);
st.push(_c);
st.push(_b);
}
}汉诺塔 非递归
最新推荐文章于 2023-10-06 21:58:38 发布
本文介绍了一种使用栈来解决汉诺塔问题的方法。通过递归思想将问题规模缩小,并利用栈的数据结构特性实现盘子的有效移动。文章提供了一个具体的C++实现案例。
2357

被折叠的 条评论
为什么被折叠?



