-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.c
More file actions
90 lines (74 loc) · 1.58 KB
/
Stack.c
File metadata and controls
90 lines (74 loc) · 1.58 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
#include "Stack.h"
Stack *doEmptyStack(){
Stack *address = (Stack*) calloc(1, sizeof(Stack));
if(address == NULL){
fprintf(stderr, "DO EMPTY STACK Function-> Error allocating the stack.\n");
exit(0);
}
return address;
}
int adds(Stack *stack, ItemT item){
if(stack == NULL){
fprintf(stderr, "ADDS Function -> Invalid parameter.\n");
return 0;
}
Cell *newCell = (Cell*) calloc(1, sizeof(Cell));
if(newCell == NULL){
fprintf(stderr, "ADDS Function -> Error allocating a new cell.\n");
return 0;
}
newCell->item = item;
newCell->below = stack->last;
if(stack->length == 0){
stack->first = stack->last = newCell;
}
else{
stack->last = newCell;
}
stack->length += 1;
return 1;
}
int removes(Stack *stack){
if(stack == NULL){
fprintf(stderr, "REMOVES Function -> Invalid parameter.\n");
return 0;
}
if(stack->length){
if(stack->length == 1){
stack->length--;
free(stack->last);
stack->first = stack->last = NULL;
return 1;
}
Cell *aux = stack->last;
stack->length--;
stack->last = stack->last->below;
free(aux);
return 1;
}
return 0;
}
void destroy(Stack *stack){
if(stack == NULL){
fprintf(stderr, "DESTROY Function -> Invalid parameter.\n");
return;
}
Cell *aux = stack->last;
while(aux != NULL){
stack->last = aux->below;
free(aux);
aux = stack->last;
}
free(stack);
}
void printStack(Stack *stack){
if(stack == NULL){
fprintf(stderr, "PRINT STACK Function -> Invalid parameter.\n");
return;
}
Cell *walker = stack->last;
while(walker != NULL){
printf("%d\n", walker->item);
walker = walker->below;
}
}