个人信息:就读于燕大本科软件工程专业 目前大三;
本人博客:google搜索“cqs_2012”即可;
个人爱好:酷爱数据结构和算法,希望将来搞科研为人民作出自己的贡献;
博客内容:汉诺塔问题;
博客时间:2014-4-7
编程语言:C++ (面向过程)
编程坏境:Windows 7 专业版
编程工具:vs2008 32位编译器
有些问题已经老掉牙,但是那不是对自己。
汉诺塔问题。
递归解决问题
1. 递归解决 从A 到 B 移动 n-1 个元素
2. 把最大的底层从 A 移动到 C
3.递归解决 从 B 到 C 移动 n-1 个元素
时间效率真慢,不过能解决问题,
一开始 A 从上到下 一次 1 2 3 4 5 6 7 8 9 10
移动完之后 C 从上到下 是 1 2 3 4 5 6 7 8 9 10
test.cpp
#include<iostream> #include<stack> using namespace std; // function: make n elems from A to C with B // input: three stacks,and elem number // output: void // 功能: 借助B移动n个元素从A到C void _One_to_anohter(stack<int> * A,stack<int> *B,stack<int>*C,int n); int main() { stack<int> * A = new stack<int>; stack<int> * B = new stack<int>; stack<int> * C = new stack<int>; int n = 10 ; for( int i = n;i>0;i-- ) { A->push( i ); } _One_to_anohter(A,B,C,n); cout<<"C"<<endl; while(! C->empty()) { cout<<C->top()<<endl; C->pop(); } system("pause"); return 0; } // function: make n elems from A to C with B // input: three stacks,and elem number // output: void // 功能: 借助B移动n个元素从A到C void _One_to_anohter(stack<int> * A,stack<int> *B,stack<int>*C,int n) { if(A != NULL && B != NULL && C != NULL && n>0 && n <= A->size()) { if(n == 1) { int data = A->top(); C->push(data); A->pop(); } else { _One_to_anohter(A,C,B,n-1); int data = A->top(); C->push(data); A->pop(); _One_to_anohter(B,A,C,n-1); } } else { cout<<"exception of function _One_to_anohter input"<<endl; } }
原文:http://blog.csdn.net/cqs_experiment/article/details/23138883