#ifndef STACK_H #define STACK_H /////////////////////////////////////////////////////////////////// // stack.h - template-based, fixed array, stack class // // // // This module is used as an example of how you would use the // // test harness, provided by the Test and Suite modules. // // // // Language: Visual C++, ver 6.0, SP 4 // // Platform: Dell XPS1000, Windows 2000 Professional, SP 1 // // Author: Jim Fawcett, CST 2-187, Syracuse University // // jfawcett@twcny.rr.com, 315-443-3948 // // Source: // // The origianl design and implementation are by Chuck // // Allison (see ref, below), but I have modified his code // // and so take responsibility for this product. // /////////////////////////////////////////////////////////////////// #include #include #include #include #include using std::logic_error; using std::string; using std::bad_alloc; // MS std namespace work-around #ifndef _MSC_VER using std::size_t; #endif /////////////////////////////////////////////////////////////////// // define stack error exception class // class StackError : public logic_error { public: StackError(const string& s) : logic_error(s) {} }; // /////////////////////////////////////////////////////////////////// // declare stack class // template class Stack { public: Stack(size_t) throw(StackError, bad_alloc); ~Stack(); void push(const T&) throw(StackError); T pop() throw(StackError); T top() const throw(StackError); size_t size() const; private: T* data; size_t max; // size of allocated memory size_t ptr; // number of items on stack }; //----< destructor >----------------------------------------------- template inline Stack::~Stack() { delete [] data; max = ptr = 0; } //----< return number of items on stack >-------------------------- template inline size_t Stack::size() const { return ptr; } //----< constructor >---------------------------------------------- template Stack::Stack(size_t siz) throw(StackError, bad_alloc) { if (siz <= 0) throw StackError("bad size in Stack(size_t)"); data = new T[siz]; max = siz; ptr = 0; } // //----< push an item onto stack >---------------------------------- template void Stack::push(const T& x) throw(StackError) { if (ptr == max) throw StackError("stack overflow"); assert(ptr < max); data[ptr++] = x; } //----< pop an item off stack >------------------------------------ template T Stack::pop() throw(StackError) { if (ptr == 0) throw StackError("stack underflow"); return data[--ptr]; } //----< return top item on stack without popping >----------------- template T Stack::top() const throw(StackError) { if (ptr <= 0) throw StackError("stack underflow"); return data[ptr - 1]; } #endif