-
Notifications
You must be signed in to change notification settings - Fork 0
/
tower.c
104 lines (85 loc) · 1.78 KB
/
tower.c
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
/*
* tower.c
*
*/
#include "tower.h"
#include "disc.h"
#include <stdlib.h>
#include <stdio.h>
static int processMove(Tower *source, Tower *dest);
static int verify(Tower *tower);
int insertDics(int size, Tower *tower) {
Disc *disc = malloc(sizeof(* disc));
disc->size = size;
disc->next = NULL;
if(tower->top != NULL) { /* NULL */
disc->next = tower->top;
}
tower->top = disc;
return 0;
}
int move(Tower *source, Tower *dest) {
if(source->top != NULL && dest->top != NULL && dest->top->size < source->top->size) {
return -2; /* dest has smaller disc*/
}
return processMove(source, dest);
}
int verify(Tower *tower) {
Disc *disc;
int prev = -1;
disc = tower->top;
while(disc != NULL) {
if (prev > -1 && disc->size <= prev ) {
printf("ERROR in tower: %i", tower->number);
exit(1);
}
disc = disc->next;
}
return 0;
}
int undoMove(Tower *source, Tower *dest) {
verify(source);
verify(dest);
return processMove(dest, source);
}
int isDestTowerComplete(Tower *tower, int discCount) {
Disc *disc;
int index = 1;
disc = tower->top;
while(disc != NULL) {
/*printf("%i - %i", index, disc->size);*/
if (disc->size != index++) {
return 0;
}
disc = disc->next;
}
return index == discCount+1 ? 1 : 0;
}
int processMove(Tower *source, Tower *dest) {
Disc* tmp;
if(source->top == NULL) {
return -1; /* source has no disc */
}
tmp = source->top;
source->top = source->top->next;
tmp->next = dest->top;
dest->top = tmp;
return dest->top->size;
}
void freeDiscs(Tower *tower) {
Disc *disc;
disc = tower->top;
while(disc != NULL) {
Disc* tmp = disc->next;
free(disc);
disc = tmp;
}
tower->top = NULL;
}
void freeTowers(Tower* towers, int* towersCount) {
int i;
for(i = 0; i < *towersCount; i++) {
freeDiscs(&towers[i]);
}
free(towers);
}