Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * [StackClass.h]
- *
- * Generic (LIFO) Stack class.
- *
- * This Stack has been implemented with templates to allow it to accommodate virtually any data type,
- * and the size of the Stack is determined dynamically at runtime.
- *
- * There is also a new function: peek(), which, given a whole number 'Depth', returns the Stack
- * element which is 'Depth' levels from the top.
- */
- #ifndef __StackClassH__ // Code include guard...
- #define __StackClassH__ // ...
- #include <assert.h> // For error-checking purposes.
- /**
- * Main Structure of Stack Class:
- */
- template <class Elem>
- class Stack
- {
- public:
- Stack(int MaxSize=500);
- Stack(const Stack<Elem> &OtherStack);
- ~Stack(void);
- inline void Push(const Elem &Item); // Adds Item to the top.
- inline Elem Pop(void); // Returns Item from the top.
- inline const Elem &Peek(int Depth) const; // Peek a depth downwards.
- protected:
- Elem *Data; // The actual Data array.
- int CurrElemNum; // The current number of elements.
- const int MAX_NUM; // Maximum number of elements.
- };
- /**
- * Implementation of Stack Class:
- */
- // Stack Constructor Function:
- template <class Elem>
- Stack<Elem>::Stack(int MaxSize) :
- MAX_NUM(MaxSize) // Initialize the constant.
- {
- Data = new Elem[MAX_NUM]; // Create Stack array.
- CurrElemNum = 0;
- }
- // Stack Destructor Function:
- template <class Elem>
- Stack<Elem>::~Stack(void)
- {
- delete[] Data; // Destroy Stack array.
- }
- // Push() Function:
- template <class Elem>
- inline void Stack<Elem>::Push(const Elem &Item)
- {
- // Error Check: Make sure we are not exceeding the maximum storage space:
- assert(CurrElemNum < MAX_NUM);
- Data[CurrElemNum++] = Item;
- }
- // Pop() Function:
- template <class Elem>
- inline Elem Stack<Elem>::Pop(void)
- {
- // Error Check: Make sure we are not popping from an empty Stack:
- assert(CurrElemNum > 0);
- return Data[--CurrElemNum];
- }
- // Peek() Function:
- template <class Elem>
- inline const Elem &Stack<Elem>::Peek(int Depth) const
- {
- // Error Check: Make sure the depth does not exceed the number of elements:
- assert(Depth < CurrElemNum);
- return Data[CurrElemNum - (Depth + 1)];
- }
- #endif // __StackClassH__
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement