Algorithms: Stack

Simple implementation of Stack with exception handling in C++ using templates

#include<iostream.h>
template <class T>
  class StackItem {
    T item;

    public:
      StackItem<T> *next;
      T GetItem() { return item; }
      StackItem(T data) {
        this->item = data;
      }
};

template <class T>
  class Stack {
    StackItem<T> *top;
      public:
        Stack() {
          this->top = NULL;
        }

        void Push(T data) {
          StackItem<T> *it = new StackItem<T>(data);
          if(top == NULL) {
            top = it;
            top->next = NULL;
          } else {
            it->next = top;
            top = it;
          }
        }

        T Pop() {
          if(top == NULL) {
            throw "Stack is empty !!!";
          } else {
            StackItem<T> *it = top;
            top = it->next;
            return it->GetItem();
          }
        }
};

int main (int argc, char* argv) {
  Stack<int> stack;
// Add some items
  for(int i = 0; i<6; i++) {
    stack.Push(i);
    cout << "Stack loaded with new value: " << i << endl;
  }
// Print output with some indexes out of range
  for(int i = 0; i<7; i++) {
    try {
      int value = stack.Pop();
      cout << "Value removed from stack: " << value << endl;
    } catch (const char* err_msg) {
      cout << err_msg << endl;
    }
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *