Tower of Hanoi C++(using recursion)
I wrote the following code as a practice exercise.
I'm getting incorrect output when i print the destination stack.
Can anyone please point out where i'm going wrong ?
//Tower of Hanoi using Stacks!
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class Stack
{
private:
int *t;
int length, top;
public:
Stack(int len)
{
length=len;
t= new int[len];
top=-1;
}
~Stack()
{delete []t;}
void push(int d)
{
top++;
t[top]=d;
}
int pop()
{
top--;
return t[top+1];
}
void printstack()
{
int cur=top;
while(cur>-1)
{cout<<t[cur]<<endl;cur--;}
}
};
void MoveTowerofHanoi(int disk, Stack *source, Stack *temp, Stack
*destination)
{
if (disk==0)
{destination->push(source->pop());}
else
{
MoveTowerofHanoi(disk-1,source,temp,destination);
destination->push(source->pop());
MoveTowerofHanoi(disk-1,temp,destination,source);
}
}
void main()
{
clrscr();
int disks;
cout<<"Enter the number of disks!"<<endl;
cin>>disks;
Stack* source=new Stack(disks);
for(int i=0;i<disks;i++){source->push(disks-i);}
cout<<"Printing Source!"<<endl;
source->printstack();
Stack* temp=new Stack(disks);
Stack* destination=new Stack(disks);
MoveTowerofHanoi(disks,source,temp,destination);
cout<<"Printing Destination!"<<endl;
destination->printstack();
getch();
}
Here's the output i'm getting:
Enter the no. of disks!
3
Printing Source!
1
2
3
Printing Destination!
-4
No comments:
Post a Comment