As a practical exercise, I wrote the following code.
I get the wrong output when printing the target stack.
Can anyone point out where I'm wrong?
//Tower of Hanoi using Stacks!
Here's the output I get:
Enter the no. of disks! 3 Printing Source! 1 2 3 Printing Destination! -4
After editing, the code is as follows:
void MoveTowerofHanoi(int disk, Stack *source, Stack *destination, Stack *temp) { if (disk==1) { destination->push(source->pop()); } else { MoveTowerofHanoi(disk-1,source,temp,destination); destination->push(source->pop()); MoveTowerofHanoi(disk-1,temp,destination,source); } }
first mistake:
void MoveTowerofHanoi(int disk, Stack *source, Stack *temp, Stack *destination)
second:
if (disk==0)
Many thanks to all for your help!
Changes to the stack class:
void push(int d) { if(top<length-1) { top++; t[top]=d; } } int pop() { if(top>-1) { top--; return t[top+1]; } }
source share