Algorithms: Queue

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

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

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

template <class T>
  class Queue {
    QueueItem<T> *first;
    QueueItem<T> *last;
    public:
      Queue() {
        this->first = NULL;
        this->last = this->first;
      }

      void Push(T data) {
        QueueItem<T> *it = new QueueItem<T>(data);
        it->next = NULL;

        if(first == NULL) {
          first = it;
          last = it;
          first->next = NULL;
          last->next = NULL;
        } else {
          last->next = it;
          last = it;
        }
      }

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

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

Leave a Reply