#include #include "stack.h" typedef struct stacknode { Jval val; struct stacknode *link; } StackNode; typedef struct { StackNode *top; int size; } TrueStack; /* allocates an empty stack. */ Stack new_stack() { TrueStack *ts; ts = (TrueStack *) malloc(sizeof(TrueStack)); ts->top = NULL; ts->size = 0; return (Stack) ts; } /* pushes a new piece of data onto the stack */ void stack_push(Stack s, Jval val) { StackNode *sn; TrueStack *ts; ts = (TrueStack *) s; /* Create the new node */ sn = (StackNode *) malloc(sizeof(StackNode)); sn->val = val; sn->link = ts->top; /* Put the new node at the beginning of the stack */ ts->top = sn; ts->size++; } /* returns the top value on the stack without popping it */ Jval stack_top(Stack s) { TrueStack *ts; if (stack_empty(s)) { fprintf(stderr, "Error: Stack_top called on an empty stack\n"); exit(1); } ts = (TrueStack *) s; return ts->top->val; } /* pops a value off the stack and returns it */ Jval stack_pop(Stack s) { Jval val; StackNode *sn; TrueStack *ts; val = stack_top(s); ts = (TrueStack *) s; sn = ts->top; ts->top = sn->link; ts->size--; free(sn); return val; } int stack_size(Stack s) { TrueStack *ts; ts = (TrueStack *) s; return ts->size; } int stack_empty(Stack s) { return (stack_size(s) == 0); } void free_stack(Stack s) { TrueStack *ts; while (!stack_empty(s)) (void) stack_pop(s); ts = (TrueStack *) s; free(ts); }