// Written in 2521 24T2 lecture by Sim Mautner #include "Stack.h" #include #include #include #define START_SIZE 100 // from .h file: typedef struct stack * Stack; struct stack { Item *items; int size; int capacity; }; // same as: struct stack * StackNew(void) { Stack StackNew(void) { Stack new_stack = malloc(sizeof(struct stack)); if (new_stack == NULL) { fprintf(stderr, "error: out of memory\n"); exit(EXIT_FAILURE); } // same as: struct stack * new_stack = malloc(sizeof(struct stack)); new_stack->items = malloc(sizeof(Item) * START_SIZE); if (new_stack->items == NULL) { fprintf(stderr, "error: out of memory\n"); exit(EXIT_FAILURE); } new_stack->size = 0; new_stack->capacity = START_SIZE; return new_stack; } void StackFree(Stack s) { // Step 1: Free all pointers within the struct free(s->items); // Step 2: Free main struct free(s); } void StackPush(Stack s, Item it) { // 1. If our array isn't big enough for more items, grow it if (s->size >= s->capacity) { s->items = realloc(s->items, s->capacity*2); if (s->items == NULL) { fprintf(stderr, "error: out of memory\n"); exit(EXIT_FAILURE); } s->capacity = s->capacity*2; } // 2. Put item into stack s->items[s->size] = it; s->size++; } Item StackPop(Stack s) { // Check there is something to pop (Should always be the case if the user is using the ADT as specified in .h file) assert(s->size > 0); // Pop item s->size--; return s->items[s->size]; } int StackSize(Stack s) { return s->size; } Item StackPeek(Stack s) { assert(s->size > 0); return s->items[s->size-1]; }