[prev] 105 [next]

Stack as ADO (cont)

Implementation (a file named stack.c):

#include "stack.h"
#include <assert.h>

// define the Data Structure
typedef struct {
   int item[MAXITEMS];
   int top;
} stackRep;

// define the Data Object
static stackRep stackObject;

// set up empty stack
void StackInit() {
   stackObject.top = -1;
}

// check whether stack is empty
int StackIsEmpty() {
   return (stackObject.top < 0);
}




// insert int on top of stack
void StackPush(int v) {
   assert(stackObject.top < MAXITEMS-1);
   stackObject.top++;
   int i = stackObject.top;
   stackObject.item[i] = v;
}

// remove int from top of stack
char StackPop() {
   assert(stackObject.top > -1);
   int i = stackObject.top;
   int v = stackObject.item[i];
   stackObject.top--;
   return v;
}


  • assert(test) terminates program with error message if test fails
  • static Type Var declares Var as local to stack.c