-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTowerOfHanoiStacks.cpp
More file actions
147 lines (122 loc) · 2.44 KB
/
TowerOfHanoiStacks.cpp
File metadata and controls
147 lines (122 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#include <bits/stdc++.h>
using namespace std;
struct Stack
{
int size;
int top;
int *s;
};
struct Stack *createStack(int size);
void push(struct Stack *stk, int x);
int pop(struct Stack *stk);
void tower(int disks, struct Stack *source, struct Stack *inter, struct Stack *dest);
int main()
{
// number of disks
int n = 3;
// three stacks
struct Stack *source, *inter, *dest;
// create stacks
source = createStack(n);
inter = createStack(n);
dest = createStack(n);
tower(n, source, inter, dest);
delete source, inter, dest;
}
// METHOD FOR CREATING THE STACKS
struct Stack *createStack(int size)
{
struct Stack *stk;
stk->size = size;
stk->s = new int[stk->size];
stk->top = -1;
return stk;
}
bool isEmpty(struct Stack stk)
{
return stk.top == -1;
}
bool isfull(struct Stack stk)
{
return stk.size == stk.top - 1;
}
void push(struct Stack *stk, int x)
{
if (stk->size == stk->top - 1)
{
cout << "Stack Overflow";
return;
}
stk->top++;
stk->s[stk->top] = x;
}
int pop(struct Stack *stk)
{
if (stk->top == -1)
{
return -1;
}
int x = stk->s[stk->top];
stk->top--;
return x;
}
void move(int disk, char from_Rod, char to_Rod)
{
cout << "Move " << disk << " from " << from_Rod << " to " << to_Rod << "\n";
}
void moveDisk(struct Stack *source, struct Stack *dest, char s, char d)
{
int topS = pop(source);
int topD = pop(dest);
if(topS == -1)
{
push(source, topD);
move(topD,d,s);
}
else if(topD == -1)
{
push(dest,topS);
move(topS,s,d);
}
else if(topS > topD)
{
push(source, topS);
push(source, topD);
move(topD,s,d);
}
else
{
push(dest, topD);
push(dest, topS);
move(topS,s,d);
}
}
void tower(int disks, struct Stack *source, struct Stack *inter, struct Stack *dest)
{
char S = 'S', I = 'A', D = 'D';
if(disks % 2 == 0)
{
char temp = D;
D = I;
I = temp;
}
for(int i=disks; i>=1; i--)
{
push(source,i);
}
for (int i = 1; i <= pow(2,disks) - 1; i++)
{
if (i % 3 == 1)
{
moveDisk(source,dest,S,D);
}
else if (i % 3 == 2)
{
moveDisk(source,inter,S,I);
}
else if (i % 3 == 0)
{
moveDisk(inter,dest,I,D);
}
}
}