careercup3.4

经典的汉诺塔问题

/*In the classic problem of the Towers of Hanoi, you have 3 rods and N disks of different 
sizes which can slide onto any tower   The puzzle starts with disks sorted in ascending 
order of size from top to bottom (e g , each disk sits on top of an even larger one)  You 
have the following constraints: 
(A) Only one disk can be moved at a time 
(B) A disk is slid off the top of one rod onto the next rod  
(C) A disk can only be placed on top of a larger disk 
Write a program to move the disks from the first rod to the last using Stacks
*/
#include <iostream>
#include <vector>
#define N 5
using namespace std;
class Node{
public:
	int data;
    Node* next;
	Node(){this->next = 0;}
	Node(int a, Node* n=0):data(a),next(n){}
};

class Stack{
public:	
	Node* top;
	int size;
	Stack():top(0),size(0){	}
	~Stack();

	Node* pop();
	void push(int);
	void push(Node*);
	void print()const{
		Node* p = top;
		 while(p)
		{
		  cout<<p->data<<" ";
		  p = p->next;
		}
		cout<<endl;
	}
};

Stack::~Stack(){
	while(top){
	   Node* p =pop();
	   delete p;
	}
}

Node* Stack::pop(){
	if(!top) return 0;

	Node* p = top;
	top = top->next;
	return p;
	size--;
}

void Stack::push(int k){
	Node* p = top;
	top = new Node(k,p);
	size++;
}

void Stack::push(Node* k){
	k->next = top;
	top = k;
	size++;
}
Stack tower[3];
int count = 0;
void Hanoi(int n, int begin, int buff, int destin){
	if(n > 0){
		Hanoi(n-1,begin,destin,buff);
		tower[destin].push(tower[begin].pop());
		cout<<"Put the "<<tower[destin].top->data<<"th plate from "<<begin
			<<" to "<<destin<<endl;
		count++;
		Hanoi(n-1,buff,begin,destin);
	}
}

int main(){
	for(int i = N; i>= 1; i--)
		tower[0].push(i);
	Hanoi(N,0,1,2);
	cout<<"Need "<<count<<" operation."<<endl;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值