//Stack.cpp /* Stack.cpp implements some of the operations of the 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 ------------------------------------------------------------*/ #include using namespace std; #include "Stack.h" // Definition of push() void Stack::push(const StackElement & value) { if (myTop < STACK_CAPACITY - 1) { //Preserve stack invariant ++myTop; myArray[myTop] = value; } else cerr << "*** Stack full -- can't add new value ***\n" "Must increase value of STACK_CAPACITY in Stack.h\n"; } // Definition of display() void Stack::display(ostream & out) const { for (int i = myTop; i >= 0; i--) out << myArray[i] << endl; } // Definition of top() StackElement Stack::top() const { if (myTop >= 0) return (myArray[myTop]); else { cerr << "*** Stack is empty " " -- returning garbage ***\n"; return myArray[STACK_CAPACITY-1]; } }