Advertisement
Leedwon

Untitled

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