Advertisement
Leedwon

Untitled

Mar 26th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.45 KB | None | 0 0
  1. #ifndef MYSTACK_H_
  2. #define MYSTACK_H_
  3.  
  4. template <typename Type>
  5. class Stack {
  6. private:
  7.     struct Node { Type item; Node * next; };
  8.     Node *mFront;
  9.     Node *mRear;
  10.     int mSize;
  11.     int mItemCount;
  12. public:
  13.     Stack(int size);
  14.     Type pop();
  15.     void push(const Type &itemToAdd);
  16.     bool isEmpty() { return mItemCount == 0; }
  17.     bool isFull() { return mItemCount == mSize; }
  18.     ~Stack();
  19. };
  20.  
  21. template<typename Type>
  22. Stack<Type>::Stack(int size) {
  23.     mSize = size;
  24.     mItemCount = 0;
  25.     mFront = mRear = nullptr;
  26. }
  27.  
  28. template<typename Type>
  29. void Stack<Type>::push(const Type &itemToAdd) {
  30.     if (isFull()) {
  31.         throw("full stack exception");
  32.     } else {
  33.         Node *add = new Node;
  34.         add->item = itemToAdd;
  35.         add->next = nullptr;
  36.         mItemCount++;
  37.         if (mFront == nullptr) // if stack is empty
  38.             mFront = add;
  39.         else
  40.             add->next = mRear; // this item now points into one earlier  
  41.         mRear = add; // add this item as last item
  42.     }
  43. }
  44. template<typename Type>
  45. Type Stack<Type>::pop() {
  46.     if (mFront == nullptr) {
  47.         throw("empty stack exception");
  48.     } else {
  49.         Node *temp = mRear;
  50.         Type returnType = temp->item;
  51.         mItemCount--;
  52.         mRear = mRear->next; // sets penultimate item to be last one
  53.         if (mItemCount == 0)
  54.             mFront = nullptr;
  55.         delete temp;
  56.         return returnType;
  57.     }
  58. }
  59. template<typename Type>
  60. Stack<Type>::~Stack() {
  61.     Node *temp;
  62.     while (mFront != nullptr && !isEmpty()) {
  63.         temp = mFront;
  64.         mFront = mFront->next;
  65.         delete temp;
  66.     }
  67. }
  68. #endif // !MYSTACK_H_
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement