借助堆栈以非递归(循环)方式求解汉诺塔的问题(n, a, b, c),即将N个盘子从起始柱(标记为“a”)通过借助柱(标记为“b”)移动到目标柱(标记为“c”),并保证每个移动符合汉诺塔问题的要求。
输入格式:
输入为一个正整数N,即起始柱上的盘数。
输出格式:
每个操作(移动)占一行,按柱1 -> 柱2的格式输出。
输入样例:
3
结尾无空行
输出样例:
a -> c
a -> b
c -> b
a -> c
b -> a
b -> c
a -> c
结尾无空行
#include#include using namespace std; typedef struct node{ int num; char a; char b; char c; }Node; struct node N,t; int main() { int n; cin>>n; stack S; N.num=n; N.a='a'; N.b='b'; N.c='c'; S.push(N); while(!S.empty()){ N=S.top(); S.pop(); if(N.num==1)printf("%c -> %cn",N.a,N.c); else { t.num=N.num-1;t.a=N.b;t.c=N.c;t.b=N.a; S.push(t); t.num=1;t.a=N.a;t.b=N.b;t.c=N.c; S.push(t); t.num=N.num-1;t.a=N.a;t.c=N.b;t.b=N.c; S.push(t); } } return 0; }
用了stl里的stack。



