summaryrefslogtreecommitdiff
path: root/src/stack.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/stack.c')
-rw-r--r--src/stack.c99
1 files changed, 72 insertions, 27 deletions
diff --git a/src/stack.c b/src/stack.c
index d29d1a7..afdf243 100644
--- a/src/stack.c
+++ b/src/stack.c
@@ -1,55 +1,100 @@
-#include "stack.h"
#include <stdio.h>
+#include <stdlib.h>
+#include "stack.h"
-#define STACK_SIZE 100
+void stackPush(struct stack_st* s, int val){
-struct stack_st stack = { .len = 0, .arr = {0}};
+ if (s->len == 0 || s->arr == NULL){
-// Functions
+ // Peame küsima mälu
+ s->size = 1;
+ //printf("yeet: %d\n", *(s->arr));
+ s->arr = (int*) malloc(s->size * sizeof(int));
-void stackPush(int val){
- if (stack.len >= STACK_SIZE){
- printf("Stack overrflow\n");
- return;
+ // 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;
}
- stack.arr[stack.len] = val;
- stack.len++;
- return;
}
-int stackPop(void){
- if (stackIsEmpty()){
- return 0;
+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;
}
- int stackPopped = stack.arr[--stack.len];
- return stackPopped;
+
+ if (s->len == 0)
+ stackFree(s);
+
+ return x;
+}
+
+void stackFree(struct stack_st *s){
+ free(s->arr);
+ s->arr = NULL;
}
-int stackIsEmpty(void) {
- return !(stack.len > 0);
+int stackIsEmpty(struct stack_st *s) {
+ return !(s->len > 0);
}
-int stackPeek(){
- // To avoid funking up the stack.len
- if (stackIsEmpty()) return 0;
- else if (stack.len == 1) return stack.arr[1];
+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();
- stackPush(x);
+ int x = stackPop(s);
+ stackPush(s, x);
return x;
}
}
-void stackPrint(){
+void stackPrint(struct stack_st *s){
while(1){
- if(stackIsEmpty())
+ if(stackIsEmpty(s))
break;
- int x = stackPop();
+ int x = stackPop(s);
printf("%d\n", x);
}
return;