Leedwon

Untitled

Mar 26th, 2018
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.26 KB | None | 0 0
  1. #pragma once
  2.  
  3. template <typename Type>
  4. class DynArrBasedStack {
  5. private:
  6.     Type *mStack;
  7.     int mSize;
  8.     int mItemCount;
  9. public:
  10.     DynArrBasedStack(int s);
  11.     Type pop();
  12.     void push(const Type &itemToAdd);
  13.     bool isEmpty() { return mItemCount == 0; }
  14.     bool isFull() { return mItemCount == mSize; }
  15.     ~DynArrBasedStack();
  16. };
  17.  
  18. template<typename Type>
  19. DynArrBasedStack<Type>::DynArrBasedStack(int s) {
  20.     mSize = s;
  21.     mItemCount = 0;
  22.     mStack = new Type[mItemCount];
  23. }
  24.  
  25. template<typename Type>
  26. Type DynArrBasedStack<Type>::pop() {
  27.     if (isEmpty())
  28.         throw("empty stack exception");
  29.     Type temp = mStack[mItemCount - 1];
  30.     mItemCount--;
  31.     Type *newStack = new Type[mItemCount];
  32.     for (int i = 0; i < mItemCount; i++)
  33.         newStack[i] = mStack[i];
  34.     mStack = newStack;
  35.     return temp;
  36. }
  37.  
  38. template<typename Type>
  39. void DynArrBasedStack<Type>::push(const Type& itemToAdd) {
  40.     if (isFull())
  41.         throw("full stack exception");
  42.     mItemCount++;
  43.     Type *newStack = new Type[mItemCount];
  44.     for (int i = 0; i < mItemCount - 1; i++) { //assinging values from old array to new one
  45.         newStack[i] = mStack[i];
  46.     }
  47.     newStack[mItemCount - 1] = itemToAdd;  // adding new item
  48.     mStack = newStack;
  49. }
  50.  
  51. template<typename Type>
  52. DynArrBasedStack<Type>::~DynArrBasedStack() {
  53.     delete[] mStack;
  54. }
Add Comment
Please, Sign In to add comment