汉诺塔:汉诺塔(又称河内塔)问题是源于印度一个古老传说的益智玩具。大梵天创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上按照大小顺序摞着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 funs
if (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;
}