// Stack implemented as a linked list -- Pouya Larjani // based on stack_as_linked_list.c by W. M. Farmer #include #include #include "stack.h" // Make a new stack stack bottom() { stack s = (stack)malloc(sizeof(struct stack_s)); s->top = NULL; s->height = 0; return s; } // Height of the stack int height(stack s) { return s->height; } // Top element of the stack element top(stack s) { if (s->height > 0) return s->top->data; fprintf(stderr, "Stack is empty\n"); // printf(x) == fprintf(stdout, x) return NULL; } // Pop the top element of a stack void pop(stack s) { if (s->height == 0) fprintf(stderr, "Stack is empty\n"); else { node n = s->top; s->top = n->below; s->height--; free(n); } } // Push an element to the top of the stack void push(stack s, element data) { // Make the new node node n = (node)malloc(sizeof(struct node_s)); n->data = data; n->below = s->top; s->top = n; s->height++; } // Print a stack void print_stack(stack s) { printf("Stack: Height=%d", s->height); for (node n = s->top; n != NULL; n=n->below) printf(" -> [%s]", n->data); printf("\n"); } /* for (init; cond; step) { ... } ==> init; while (cond) { ...; step; } */