经典的汉诺塔问题
/*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;
}