标题4147 汉诺塔问题(栈写法)
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<cstring>
#include<stack>
using namespace std;
class problem{
public:
int min_No,max_No;
char start,middle,target;
problem(){}
problem(int n_min,int n_max,char start_,char middle_,char target_):min_No(n_min),max_No(n_max),start(start_),middle(middle_),target(target_){}
problem operator=(problem & p){
min_No=p.min_No;max_No=p.max_No;start=p.start;middle=p.middle;target=p.target;
}
};
int main(){
int n;
char a,b,c;
cin>>n;
cin>>a>>b>>c;
stack<problem> problem_stack;
problem new_problem(1,n,a,b,c),temp;
problem_stack.push(new_problem);
while(!problem_stack.empty()){
temp=problem_stack.top();
problem_stack.pop();
if(temp.min_No==temp.max_No)
cout<<temp.min_No<<":"<<temp.start<<"->"<<temp.target<<endl;
else{
problem problem1(temp.min_No,temp.max_No-1,temp.middle,temp.start,temp.target);
problem_stack.push(problem1);
problem problem2(temp.max_No,temp.max_No,temp.start,temp.middle,temp.target);
problem_stack.push(problem2);
problem problem3(temp.min_No,temp.max_No-1,temp.start,temp.target,temp.middle);
problem_stack.push(problem3);
}
}
return 0;
}
算法总结:
【递归的本质】:
递归的实现是基于对栈的操作,递归的最底层(可以直接解决的问题是栈最上层,即立即出栈的)
C++用法总结:
1.stack的:删除pop(),加入push(),取顶元素top()函数的用法。
2.直接使用递归的时候如果数据非常大有可能导致栈溢出,如果实在不能用递归函数解决问题,就要用栈来模拟一个递归过程。
见 https://blog.csdn.net/bobbypollo/article/details/79891556