汉诺塔(用栈实现)

#include
#include
using namespace std;

class Hanoi
{
public:
	Hanoi() {};
	~Hanoi() {};
	friend void hanoiTowers(int);
	void hanoiTowers(int n, int a, int b, int c);
private:
	stack *s[4];
};

void Hanoi::hanoiTowers(int n, int a, int b, int c)//从a移到b借助c
{
	int i;//碟子的编号
	if (n > 0)
	{
		hanoiTowers(n - 1, a, c, b);
		s[a]->pop();
		s[b]->push(i);
		cout << "从" << a << "移到" << b << endl;
		hanoiTowers(n - 1, c, b, a);
	}
}

void hanoiTowers(int n)
{
	Hanoi h;
	h.s[1] = new stack;
	h.s[2] = new stack;
	h.s[3] = new stack;
	for (int i = n; i > 0; i--)
		h.s[1]->push(i);//初始化,将碟子i放到塔1上
		h.hanoiTowers(n, 1, 2, 3);
	
}





void main()
{
	hanoiTowers(3);
	system("pause");
}

用栈实现的汉诺塔,原理和上篇一致。

你可能感兴趣的:(汉诺塔)