汉诺塔递归实现与栈实现
来源:互联网 发布:程序员团队名称大全 编辑:程序博客网 时间:2024/06/05 20:57
汉诺塔:汉诺塔(又称河内塔)问题是源于印度一个古老传说的益智玩具。大梵天创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上按照大小顺序摞着64片黄金圆盘。大梵天命令婆罗门把圆盘从下面开始按大小顺序重新摆放在另一根柱子上。并且规定,在小圆盘上不能放大圆盘,在三根柱子之间一次只能移动一个圆盘。
数据结构书上的代码如下:
#include<iostream>#include<array>#include<stack>using namespace std;//把塔x顶部的n个碟子移到塔y//用塔Z做中转地void towerOfHanoi(int n, int x, int y, int z){if (n > 0){towerOfHanoi(n - 1, x, z, y);cout << "Move top disk for tower " << x << " to top of tower " << y << endl;towerOfHanoi(n - 1, z, y, x);}return;}//用栈实现汉诺塔的问题template<class T>void changeLength1D(T*&a, int oldLength, int newLength){//更改长度if (newLength < 0){throw("wrong ");}T* temp = new T[newLength];int number = min(oldLength, newLength);copy(a, a + number, temp);delete[] a;a = temp;}template<class T>class arrayStack :public stack<T>{public:arrayStack(int initialCapacity = 10);~arrayStack() { delete[] stack; };bool empty()const { return stackTop == -1; }int size()const { return stackTop + 1; }T& top(){if (stackTop == -1){throw ("wrong");}return stack[stackTop];}void pop(){if (stackTop == -1){throw("empty");}stack[stackTop--].~T();}void push(const T& theElement);private:int stackTop;int arrayLength;T* stack;};template<class T>arrayStack<T>::arrayStack(int initialCapacity){//structure funsif (initialCapacity < 1){//ostringstream s;//s << "Initial capacity = " << initialCapacity << " Must be > 0 ";//throw(s.str());}arrayLength = initialCapacity;stack = new T[arrayLength];stackTop = -1;}template<class T>void arrayStack<T>::push(const T& theElement){if (stackTop == arrayLength - 1){changeLength1D(stack, arrayLength, 2 * arrayLength);arrayLength *= 2;}stack[++stackTop] = theElement;}arrayStack<int>tower[4];void moveAndShow(int, int, int, int);void showState(){int d = tower[3].size();for (int i = 0; i < d; i++)cout << tower[3].top() << endl;}void towerOfHanoi(int n){for (int d = n; d > 0; d--){tower[1].push(d);}moveAndShow(n, 1, 2, 3);}void moveAndShow(int n, int x, int y, int z){//把塔x顶部的n个碟子移到塔y,显示移动后的布局//用塔Z做中转站if (n > 0){moveAndShow(n - 1, x, z, y);int d = tower[x].top();tower[x].pop();tower[y].push(d);showState();moveAndShow(n - 1, z, y, x);}}int main(){int a = 2;towerOfHanoi(2);//栈实现cout << endl;towerOfHanoi(2, 1, 2, 3);//递归函数实现return 0;}
阅读全文
0 0
- 汉诺塔递归实现与栈实现
- 汉诺塔 递归与非递归实现 (1)
- 汉诺塔 递归与非递归实现 (2)
- 汉诺塔的递归实现与非递归实现
- 汉诺塔(递归实现与非递归实现)
- 3.3栈与递归的实现
- 栈与递归实现Hanoi塔问题
- 栈与递归实现迷宫问题求
- 3.3栈与递归的实现
- 数据结构 汉诺塔 递归与非递归的实现
- 递归3: 汉诺塔的递归与迭代实现
- 如何用栈实现递归与非递归的转换
- 如何用栈实现递归与非递归的转换
- 如何用栈实现递归与非递归的转换
- 如何用栈实现递归与非递归的转换
- 如何用栈实现递归与非递归的转换
- 如何用栈实现递归与非递归的转换
- 如何用栈实现递归与非递归的转换
- 给一个url获得后台的数据
- 分词工具实验(代码示例)
- Qt 控件添加阴影效果
- 检测接口加密类
- 外部表与管理表
- 汉诺塔递归实现与栈实现
- 网络基础-字节序
- SSL P2822 I Will Like Matrix!
- S5PV210开发 -- UART 详解
- ROS学习问题集锦(一)_机器人仿真(by古月)学习遇到的问题
- SSO之CAS单点登录实例演示
- 1.5.2 Prime Palindromes 回文质数
- nginx负载均衡的策略
- HTML背景图铺满页面