blob: afdf243de4db2abbcbef90ec033631d2b9ea8821 (
plain)
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
|
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
void stackPush(struct stack_st* s, int val){
if (s->len == 0 || s->arr == NULL){
// Peame küsima mälu
s->size = 1;
//printf("yeet: %d\n", *(s->arr));
s->arr = (int*) malloc(s->size * sizeof(int));
// Kontrollime, et mälu allokeermisel ei tekinud probleeme
if (s->arr == NULL) {
printf("Mälu otsas\n");
return;
}
s->arr[s->len++] = val;
} // s->len == 0 end
else if (s->len == s->size){
int tmp_size = 2 * s->size;
int* tmp_arr = realloc(s->arr, tmp_size);
// Kontrollime, kas saime mälu juurde
if (tmp_arr == NULL) {
printf("Mäluala suurendamine Erroris\n");
return;
}
s->size = tmp_size;
s->arr = tmp_arr;
s->arr[s->len] = val;
s->len++;
return;
}
else {
s->arr[s->len++] = val;
}
}
int stackPop(struct stack_st *s){
int x = s->arr[--s->len];
int tmp_size = s->size / 2;
// Kui vaja s-> mälu suurust kahandada
if (s->len < tmp_size){
int* tmp_arr = realloc(s->arr, tmp_size);
if (!tmp_arr){
printf("No good, malu otsas");
return 0;
}
s->size = tmp_size;
s->arr = tmp_arr;
}
if (s->len == 0)
stackFree(s);
return x;
}
void stackFree(struct stack_st *s){
free(s->arr);
s->arr = NULL;
}
int stackIsEmpty(struct stack_st *s) {
return !(s->len > 0);
}
int stackPeek(struct stack_st *s){
// To avoid funking up the s->len
if (stackIsEmpty(s)) return 0;
else if (s->len == 1) return s->arr[1];
else{
int x = stackPop(s);
stackPush(s, x);
return x;
}
}
void stackPrint(struct stack_st *s){
while(1){
if(stackIsEmpty(s))
break;
int x = stackPop(s);
printf("%d\n", x);
}
return;
}
|