// This is an implementation file for the stack. This implementation is done // using arrays. // Sasha Vassar Week09 Lecture 15 #include #include #include "stack.h" // TODO: Define the stack structure itself, the stack structure in this case // may have an array that stores the numbers, and index which gives us the last element that went in struct stack { int stack_numbers[MAX]; int top; }; // Function to create the stack initially struct stack *create_stack(void) { //TODO: Allocate some memory to the stack structure struct stack *new_stack = malloc(sizeof(struct stack)); //TODO: Check that there was enough memory to create the stack structure if (new_stack == NULL) { printf("There is not enough memory to create a stack.\n"); exit(1); } //TODO: Initialise the stack that was created (top index) new_stack->top = 0; return new_stack; } // Function to push an item onto the stack, what are the // inputs and outputs? void push_stack(struct stack *new_stack, int item) { //TODO: Check that there is enough space in the stack array to push // a new number on if (new_stack->top == MAX) { printf("push() exceeds maximum stack size %d\n", MAX); exit(1); } //TODO: Otherwise, add the item onto the stack and change the top index new_stack->stack_numbers[new_stack->top] = item; new_stack->top = new_stack->top + 1; } // Function to pop off the stack, so we will be returning the number // that was popped off and giving the argument of the stack from which to pop int pop_stack(struct stack *new_stack) { // TODO: Boundary case: what happens if the stack is empty? This means // there is nothing to pop off if (new_stack->top == 0) { printf("There is nothing to pop off the stack, stack is empty\n"); return 1; } //TODO: Otherwise, return the top number and change the top index new_stack->top = new_stack->top - 1; return new_stack->stack_numbers[new_stack->top]; } // Function to quickly check the size of the stack int stack_size(struct stack *new_stack) { return new_stack->top; } // Function to destroy the whole stack, output is nothing since you are // destroying and input is the stack which you want to destroy void destroy_stack(struct stack *new_stack) { //TODO: How do we free the space? } // Function to print the stack void print_stack(struct stack *new_stack) { int i = 0; //TODO: What should the while loop be to print the stack? while (i < new_stack->top) { printf("%d\n", new_stack->stack_numbers[i]); //TODO: How do we access the items? i++; } }