#ifndef _STACK_H #define _STACK_H // uncomment line below if bool not built-in type //#include "bool.h" #include "vector.h" // used for stack implementation #include // abort() function const int SDEFAULT_SIZE = 10; // default initial stack size template class stack { public: // constructors/destructor stack(); // construct empty stack stack(const stack & s); // copy constructor ~stack(); // destructor // operator overloads const stack & operator = ( const stack & rhs ); // member functions const itemType & top(); // return top element (NO pop) const itemType & pop(); // pop top element bool isEmpty() const; // return true if empty, else false int length() const; // return number of elements in stack void push(const itemType & item); // push item onto top of stack void flush(); // empty the stack private: int myTop; // index of top element vector myElements; // storage for stack }; template stack::stack() : myTop(-1), myElements(SDEFAULT_SIZE) { } template stack::stack(const stack & s) : myTop(s.myTop), myElements(s.myElements) { } template stack::~stack() { // vector destructor frees memory } template const stack & stack::operator = (const stack & rhs) { if(this != &rhs) { myTop = rhs.myTop; myElements = rhs.myElements; } return *this; } template bool stack::isEmpty() const { return myTop == -1; } template int stack::length() const { return myTop+1; } template void stack::push(const itemType & item) { if( myTop + 1 >= myElements.length() ) // grow vector if necessary { myElements.resize(myElements.length() * 2); } myTop++; // new top most element myElements[myTop] = item; } template const itemType & stack::pop() { if(isEmpty()) { cerr << "error, popping an empty stack" << endl; abort(); } myTop--; return myElements[myTop+1]; } template const itemType & stack::top() { if(isEmpty()) { cerr << "error, popping an empty stack" << endl; abort(); } return myElements[myTop]; } template void stack::flush() { myTop = -1; } #endif