//Stack.h /* Stack.h provides a Stack class. * * Basic operations: * Constructor: Constructs an empty stack * empty: Checks if a stack is empty * push: Modifies a stack by adding a value at the top * top: Accesses the top stack value; leaves stack * unchanged * pop: Modifies a stack by removing the value at the * top * display: Displays all the stack elements * Class Invariant: * 1. The stack elements (if any) are stored in positions * 0, 1, . . ., myTop of myArray. * 2. -1 <= myTop < STACK_CAPACITY ------------------------------------------------------------*/ #ifndef __STACK_H #define __STACK_H const int STACK_CAPACITY = 128; typedef int StackElement; class Stack { /***** Function Members *****/ public: /*--- Constructor --- Precondition: A stack has been declared. Postcondition: Stack has been constructed as an empty stack. *********************************************/ Stack(); /* --- Is the Stack empty? --- * Returns: true if the Stack containing this * function is empty and false otherwise ***************************************************/ bool empty() const; /* --- Add a value to the stack --- * * Receive: A value to be added to a Stack * Postcondition: Value is added at top of stack * provided there's space * Output: "Stack full" message if no space *************************************************/ void push(const StackElement & value); /* --- Display values stored in the stack --- * * Receive: The ostream out * Output: Stack's contents, from top down, to out ***************************************************/ void display(ostream & out) const; /* --- Return value at top of the stack --- * Return: value at the top of nonempty Stack * Output: "Stack empty" message if stack empty ***************************************************/ StackElement top() const; /* --- Remove value at top of the stack --- * Postcondition: Top value of stack (if any) has * been removed. * Output: "Stack-empty" message if stack is empty. **************************************************/ void pop(); /***** Data Members *****/ private: StackElement myArray[STACK_CAPACITY]; int myTop; }; // end of class declaration // Definition of (default) constructor inline Stack::Stack() { myTop = -1; } // Definition of empty() inline bool Stack::empty() const { return (myTop == -1); } // Definition of pop() inline void Stack::pop() { if (myTop >= 0) // Preserve stack invariant myTop--; else cerr << "*** Stack is empty -- " "can't remove a value ***\n"; } #endif