-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstackhanoi.cpp
More file actions
60 lines (56 loc) · 1.41 KB
/
stackhanoi.cpp
File metadata and controls
60 lines (56 loc) · 1.41 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
#include <cstdio>
#include <cstdlib>
struct Node {
struct Node *nxt; // next disk
int num; // disk number
char pia; //
char pib;
char pic;
Node() {
nxt = NULL;
num = 0;
}
void set(struct Node *tmpnxt, int tmpnum, char tmpa, char tmpb, char tmpc) {
nxt = tmpnxt;
num = tmpnum; pia = tmpa; pib = tmpb; pic = tmpc;
}
};
struct Hni {
struct Node *stk; // stack
int num;
Hni() { stk = NULL; }
void push(struct Node *ptr) {
ptr->nxt = stk;
stk = ptr;
}
void pop() {
if (stk != NULL) stk = stk->nxt;
}
void hni(int tmpn) {
struct Node *tmpnode;
struct Node *current;
tmpnode = (struct Node *)malloc(sizeof(struct Node));
tmpnode->set(NULL, tmpn, 'a', 'b', 'c');
push(tmpnode);
while (stk != NULL) {
current = stk; pop();
if (current->num > 1) {
tmpnode = (struct Node *)malloc(sizeof(struct Node));
tmpnode->set(NULL, current->num - 1, current->pib, current->pia, current->pic);
push(tmpnode);
tmpnode = (struct Node *)malloc(sizeof(struct Node));
tmpnode->set(NULL, 1, current->pia, current->pib, current->pic);
push(tmpnode);
tmpnode = (struct Node *)malloc(sizeof(struct Node));
tmpnode->set(NULL, current->num - 1, current->pia, current->pic, current->pib);
push(tmpnode);
}
else printf("%c>%c ", current->pia, current->pic), free(current);
}
}
};
int main(void) {
struct Hni hni;
int n;
while (~scanf("%d", &n)) hni.hni(n), printf("\n");
}