#include #include #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; }