/* stack_as_array.c Author: W. M. Farmer Revised: November 22, 2009 Description: A simple implementation of a stack ADT in which stacks are represented as arrays with a fixed length. */ #include #include #include #define MAX_HEIGHT 10 /* Types and constants */ typedef int nat; typedef char * element; typedef struct { element contents[MAX_HEIGHT]; nat height; } stack_record; typedef stack_record * stack; /* Primitive operators */ stack bottom() { // stack new = malloc(sizeof(stack_record)); stack_record r = {{"","","","","","","","","",""},0}; stack new = &r; // stack new; // new->height = 0; return new; } nat height(stack s) { return s->height; } element top(stack s) { nat ht = s->height; if (ht == 0) { printf("Error in top: stack is empty.\n"); return 0; } else { return s->contents[ht - 1]; } } void push(element e, stack s) { nat ht = s->height; if (ht == MAX_HEIGHT) { printf("Error in push: stack is full.\n"); } else { s->contents[ht] = e; s->height = ht + 1; } } void pop(stack s) { nat ht = s->height; if (ht == 0) { printf("Error in pop: stack is empty.\n"); } else { s->height = ht - 1; } } void print(stack s) { nat ht = s->height; nat i; printf("stack contents: ["); for (i = 0; i < ht; i++) if (i + 1 == ht) printf("%s", s->contents[i]); else printf("%s,", s->contents[i]); printf("].\n"); } void dismantle(stack s) { free(s); } /* Derived operators */ bool is_empty (stack s) { return height(s) == 0; } void reset (stack s) { while (!is_empty(s)) { pop(s); } } /* Main function */ int main() { stack s = bottom(); print(s); top(s); pop(s); push("a",s); print(s); printf("Top is %s.\n",top(s)); push("b",s); print(s); push("c",s); print(s); pop(s); print(s); // reset(s); print(s); dismantle(s); print(s); return 0; }