需要一些建议在河内实施堆栈 [英] Need some advice implementing stacks in hanoi
问题描述
我对如何在C ++中的河内游戏中实现堆栈有一些疑问,我理解河内和堆栈如何工作,但我不太明白如何链接它们。
main.cpp
I have some doubts on how to implement stacks in a Hanoi game in C++, I understand how Hanoi and stacks works but I don't quite understand how to link them.
main.cpp
#include <iostream>
#include "HanoiLib.h"
#include "LibPila.h"
using namespace std;
using namespace PILA;
int main()
{
Pila P1;
int Dsk;
Dsk = P1.getData(); // Get number of disks
for(int i = 0; i < Dsk; i++) // Insert disks on source peg
{
P1.PUSH(P1.POP());
}
P1.Print(); // Print all the disks
Tower(Dsk, 1, 3, 2); // Where 1, 2 and 3 are the pegs
P1.PUSH(P1.POP()); // I'm trying to push from Dst to aux
Tower(Dsk, 3, 1, 2);
return 0;
}
HanoiLib.h
HanoiLib.h
#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_
LibPila.h
LibPila.h
#ifndef _LibPila_H_
#define _LibPila_H_
#define MAX_STACK 10 // stack max limit
using namespace std;
namespace PILA
{
class Pila
{
private:
int stack[MAX_STACK];
int top = -1;
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_
我的尝试:
只有设计以及它在理论上如何运作的流程
What I have tried:
Only the design and the flow of how this works in theory
推荐答案
此代码不执行任何操作:
This code does nothing:
P1.PUSH(P1.POP());
它从堆栈中弹出一个值并将其放回堆栈,它以ni更改结束。所有这些如果相关的代码没有被窃听。
基本上,河内的塔不需要堆栈结构,只需要一个带有每个磁盘的挂钩编号的阵列。
Nota;堆可以称为堆栈,但并不意味着使用堆栈结构。
首先,所有磁盘都在挂钩上。
基本动作。
将堆栈从启动桩移动到目标挂钩:
- 将堆栈减去最大磁盘到中间挂钩
- 将最大的磁盘移动到目标挂钩
- 将堆栈减去最大磁盘移动到目标挂钩
it pop a value from the stack and put it back on the stack, it ends with ni change. All this if related code is not bugged.
Basically, the towers of Hanoi don't need a stack structure, just an array with the peg number of each disk.
Nota; the pile can be called a stack, but do not imply using a stack structure.
To start, all disk are on peg 1.
The basic move.
To move a stack from starting peg to destination peg:
- move stack minus largest disk to intermediate peg
- move largest disk to destination peg
- move stack minus largest disk to destination peg
这篇关于需要一些建议在河内实施堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!