⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 hanor.cpp

📁 数据结构汉诺塔
💻 CPP
字号:
#include<iostream.h>
#include<iomanip.h>

class stack
{
public:
	void creatstack(int);
	bool push(int);
	bool pop();
	void output();
private:
	int basic;
	int top;
	int Array[4];
};

void stack::creatstack(int n)
{
	basic = 0;
	top   = n;
	if(n != 0)
	{
		for(int i=1; i<=n; i++)
		{
			Array[i] = 4-i;
		}
	}
}
bool stack::push(int x)
{
	if(top == 3)
	{
		cout<<""<<endl;
		return false;
	}
	else
	{
		top++;
		Array[top] = x;
		return true;
	}
}
bool stack::pop()
{
	if(top == 0)
	{
		cout<<""<<endl;
		return false;
	}
	else
	{
		top--;
		return true;
	}
}
void stack::output()
{
	for(int i=1; i<=top; i++)
	{
		cout<<setw(6)<<Array[i];
	}
	cout<<endl;
}

void move(stack & x,int n,stack & y)
{
	if(x.pop())
	{
		y.push(n);
	}
	else
	{
		cout<<"error"<<endl;
	}
}

void hanoi(int n, stack & x,stack & y, stack & z)
{
	if(n == 1)
	{
		move(x,n,z);
		cout<<"x: ";
		x.output();
		cout<<endl;
		cout<<"y: ";
		y.output();
		cout<<endl;
		cout<<"z: ";
		z.output();
		cout<<endl<<endl;
	}
	else
	{
		hanoi(n-1,x,z,y);
		move(x,n,z);
		cout<<"x: ";
		x.output();
		cout<<endl;
		cout<<"y: ";
		y.output();
		cout<<endl;
		cout<<"z: ";
		z.output();
		cout<<endl<<endl;
		hanoi(n-1,y,x,z);
	}
}

void main()
{
	stack test_1;
	test_1.creatstack(3);
	stack test_2;
	test_2.creatstack(0);
	stack test_3;
	test_3.creatstack(0);
	hanoi(3,test_1,test_2,test_3);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -