-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.c
More file actions
106 lines (90 loc) · 2.63 KB
/
Copy pathStack.c
File metadata and controls
106 lines (90 loc) · 2.63 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
#include "Stack.h"
/* Allocates memory for Stack and initializes top->NULL, count->0 */
Stack *initializeStack() {
Stack *stack;
stack = (Stack *) malloc(1 * sizeof(Stack));
if (stack == NULL) {
printMallocFailed();
exit(0);
}
stack->count = 0;
stack->top = NULL;
return stack;
}
/* Allocates memory for Stack element (doesn't initialize its fields!) */
element *allocateMemoryForStackElement() {
element *newElement;
newElement = (element *) malloc(1 * sizeof(element));
if (newElement == NULL) {
printMallocFailed();
exit(0);
}
return newElement;
}
void push(Stack *stack, int row, int col, int value) {
element *newElement = NULL;
newElement = allocateMemoryForStackElement();
/* Set newElement's fields: */
newElement->row = row;
newElement->col = col;
newElement->value = value;
/* Update stack: */
newElement->next = stack->top;
stack->top = newElement;
(stack->count)++;
}
/* Precondition: stack.isEmpty() == FALSE
* Returns pointer to top of stack element, user must free memory after using it*/
element *pop(Stack *stack) {
element *removedElement;
removedElement = stack->top;
stack->top = stack->top->next;
removedElement->next = NULL;
(stack->count)--;
return removedElement;
}
/* Returns TRUE (1) if stack->count == 0, FALSE (0) otherwise */
int isEmpty(Stack *stack) {
if (stack->count == 0) return TRUE;
else if (stack->count > 0) return FALSE;
else if (stack->count < 0) {
printErrorInCodeFlow("isEmpty", "Stack.c");
return FALSE;
}
return FALSE;
}
#ifdef OldStack
/* Precondition: boardSnapshot is a copy of the board status (its memory already allocated) */
void push(Stack *stack, BOARD boardSnapshot)
{
element *newStackElement = NULL;
newStackElement = (element *)malloc(sizeof( element)); /* Allocate memory for the "box", the stack element */
if (newStackElement == NULL) {
printMallocFailed();
exit(0);
}
newStackElement->currentBoard = boardSnapshot; /* update data */
newStackElement->next = stack->top;
stack->top = newStackElement;
stack->count++;
}
/* Precondition: stack.isEmpty() == FALSE */
BOARD pop(Stack *stack) {
/* Sanity check (to remove) */
if (stack->count <= 0) {
printErrorInCodeFlow("pop", "Stack.c");
}
BOARD board;
element *p = NULL;
board = stack->top->currentBoard;
p = stack->top;
stack->top = stack->top->next;
stack->count--;
free(p);
return board;
}
int isEmpty(Stack *stack) {
if (stack->count == 0) return TRUE;
else return FALSE;
}
#endif