|
|
Hanoi-Stack
hanoi.cpp
// Hanoi.cc
// A class to store the current state of the Towers of Hanoi puzzle.
//
//-------------------------------------------------------------------
#include "hanoi.h"
//-------------------------------------------------------------------
// The default constructor
//
Hanoi::Hanoi(): NumberPegs(3),NumberDiscs(3)
{
Peg=new stack[NumberPegs]();
for(int i=NumberDiscs;i>0;i--)
{
Peg[0].push(i);
}
}
//-------------------------------------------------------------------
// The constructor
//
Hanoi::Hanoi(int discs,int pegs) {
NumberDiscs=discs;
NumberPegs=pegs;
Peg=new stack[NumberPegs]();
for(int i=NumberDiscs;i>0;i--)
{
Peg[0].push(i);
}
}
//-------------------------------------------------------------------
// The copy constructor
//
Hanoi::Hanoi(const Hanoi& H) {
NumberDiscs=H.NumberDiscs;
NumberPegs=H.NumberPegs;
Peg=new stack[NumberPegs]();
for(int i=0;i<NumberDiscs;i++)
{
Peg[i]=H.Peg[i];
}
}
//-------------------------------------------------------------------
Hanoi::~Hanoi() {
if(Peg!=NULL)
delete []Peg;
}
//-------------------------------------------------------------------
void Hanoi::operator =(const Hanoi &H) {
if(Peg!=NULL)
delete []Peg;
NumberDiscs=H.NumberDiscs;
NumberPegs=H.NumberPegs;
Peg=new stack[NumberPegs]();
for(int i=0;i<NumberDiscs;i++)
{
Peg[i]=H.Peg[i];
}
}
//-------------------------------------------------------------------
int Hanoi::Move_Disc(int i,int j) {
if(i>=0 && i<NumberPegs && j>=0 && j<NumberPegs && !Peg[i].empty() &&
(Peg[j].empty() || Peg[i].peek() < Peg[j].peek() ) )
{
Peg[j].push(Peg[i].pop());
return 1;
}
return 0;
}
//-------------------------------------------------------------------
void Hanoi::Show_Towers() {
cout<<"\n\n\n";
int **P=new int*[NumberPegs];
for(int i=0;i<NumberPegs;i++) {
P[i]=stack2array(Peg[i],NumberDiscs);
}
for(int i=NumberDiscs-1;i>=0;i--) {
for(int j=0;j<NumberPegs;j++) {
cout.width(6);
if(P[j][i]!=0)
cout<<P[j][i];
else
cout<<"|";
}
cout<<"\n";
}
cout<<" _A_ _B_ _C_ \n\n";
cout<<"Press enter to continue.";
char a;
cin.get(a);
}
//-------------------------------------------------------------------
|