Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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

C++
#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

C++
#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

C++
#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
Posted
Updated 26-Jul-16 18:46pm
v2

1 solution

This code does nothing:
C++
P1.PUSH(P1.POP());

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
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900