我对如何在C ++中的河内游戏中实现堆栈有一些疑问,我理解河内和堆栈是如何工作的,但我不太了解如何链接它们。
每个挂钩都是一系列数字,但我不知道如何以正确的顺序将它们从一个移到另一个。
我尝试做的是将每个挂钩用作数字堆栈(数组),使用POP和PUSH移动磁盘。
可能是PUSH(Destination,POP(Source))或Destination.PUSH(POP.AUX())
其中
First peg = Source,Second peg = Destination,Third peg = Aux
# include < iostream >
# include " HanoiLib.h " // Recursive Hanoi method
# include " LibPila.h " // My stack lib
using namespace std;
using namespace PILA;
int main()
{
Pila P1; // From LibPila.h class Pila
int Dsk;
Dsk = P1.getData(); // Get the number of disks
for(int i = 0; i < Dsk; i++)
{
P1.PUSH(P1.POP()); // Fill the first peg
}
P1.Print(); // Print the disks
Tower(Dsk, 1, 3, 2); // Where 1, 2 and 3 are the pegs
P1.PUSH(P1.POP()); // This is a wrong idea of how to move the disks..
Tower(Dsk, 3, 1, 2);
return 0;
}
# ifndef _LibHanoi_H_
# define _LibHanoi_H_
using namespace std;
void Tower(int Dsk, int Src, int Dst, int aux)
{
if(Dsk > 0)
{
Tower(Dsk - 1, Src, Dst, aux);
cout << "Move disk " << Dsk << "from " << Src << "to " << aux << endl;
Tower(Dsk - 1, Dst, aux, Src);
}
}
# endif // __LibHanoi_H_
# ifndef _LibPila_H_
# define _LibPila_H_
# define MAX_STACK 10 // Max size of the stack
using namespace std;
namespace PILA
{
class Pila
{
private:
int stack[MAX_STACK]; // MAX_STACK = 10
int top = -1; // The top of the stack
public:
void PUSH(int val)
{
if(top == MAX_STACK -1 )
cout << "Stack overflow!!" << endl;
stack[++top] = val;
}
int POP()
{
if(top == -1)
cout << "There's nothing here!!" << endl;
top--;
return top;
}
int Top()
{
return stack[top];
}
void Print()
{
int i;
cout << "Stack: ";
for(i = 0; i <= top; i++)
cout << stack[i];
cout << "" << endl;
}
int getData()
{
int x;
cout << "Insert NO of disks: "<< endl;
cin >> x;
return x;
}
};
}
# endif // __LibPila_H_