Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Please help I am trying to show the output of steps of the discs moving from each tower in this tower of hanoi program using

Please help I am trying to show the output of steps of the discs moving from each tower in this tower of hanoi program using stacks. #include
#include
#include
#include "main_1.h"
#include "Hanoi.h"
using namespace std;
Stack::Stack(){
top =-1;
for(int i =0; i <3; i++){
arr[i]=0;
}
}
Stack::~Stack(){
}
bool Stack::isEmpty(){
if(top ==-1){
return true;
}
else{
return false;
}
}
bool Stack::isFull(){
if(top ==3){
return true;
}
else{
return false;
}
}
void Stack::push(int val){
if(isFull()){
cout << "Overflow" << endl;
}
else{
top++;
arr[top]=val;
}
}
int Stack::pop(){
if(isEmpty()){
cout << "stack underflow" << endl;
return 0;
}
else{
int popValue = arr[top];
arr[top]=0;
top--;
return popValue;
}
}
int Stack::count(){
return (top +1);
}
int Stack::peek(int pos){
if(isEmpty()){
cout << "Stack underflow" << endl;
return 0;
}
else{
return arr[pos];
}
}
void Stack::change(int pos, int val){
arr[pos]=val;
cout << "Value changed at position" << pos << endl;
}
void Stack::display(){
cout << "all items in stack are "<< endl;
for(int i =3; i >=0; i--){
cout << arr[i]<< endl;
}
}
void moveDisk(int disks, char fromRod, char toRod){
cout<<"Moving disk "< top2){
source.push(top1);
source.push(top2);
moveDisk(top2, d, s);
}
}
void towerOfHanoi(int disks, Stack &source, Stack &auxiliary, Stack &destination){
char s ='S', d ='D', a ='A';
if(disks %2==0){
char var = d;
d = a;
a = var;
}
int numMoves = pow(2, disks)-1;
for(int i = disks; i >=1; i--){
source.push(i);
}
for(int i =1; i <= numMoves; i++){
if(i %3==0){
moveDiskHelper(auxiliary, destination, a, d);
}
else if(i %3==2){
moveDiskHelper(source, auxiliary, s, a);
}
else if(i %3==1){
moveDiskHelper(source, destination, s, d);
}
}
}
int main(){
int numDisks =3;
Stack towerA, towerB, towerC;
for(int i = numDisks; i >0; i--){
towerA.push(i);
}
cout << "initial configuration:" << endl;
towerA.display();
towerB.display();
towerC.display();
towerOfHanoi(numDisks, towerA, towerB, towerC);
cout << "Final configuration:" << endl;
towerA.display();
towerB.display();
towerC.display();
return 0;
}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Expert Performance Indexing In SQL Server

Authors: Jason Strate, Grant Fritchey

2nd Edition

1484211189, 9781484211182

More Books

Students also viewed these Databases questions