I want to share with you a generic queue in C++ that I made for educational purposes. It is mainly composed by two classes as every LIFO stack (also known as Queue), first the Queue class that defines an interface for using our queue with the common methods (enqueue, dequeue, first, isEmpty,…) and finally the Node class that represents a node of information with a pointer to the next element.
In order to have a Generic Queue we need to parametrize that classes and if necessary, override the assignment method if we want to use a non primitive type queue.
Note: Implementation of methods must be in headers files instead of .cpp files otherwise we can get some compiler errors (tested in Visual Studio 2010)
Queue class code:
template <class T> class Queue { private: Node<T>* first; Node<T>* last; int count; public: Queue(void) { first = NULL; last = NULL; count = 0; } ~Queue(void) { while(!isEmpty()) Dequeue(); } void Enqueue(T element) { Node<T>* tmp = new Node<T>(); tmp->setData(element); tmp->setNext(NULL); if (isEmpty()) { first = last = tmp; } else { last->setNext(tmp); last = tmp; } count++; } T Dequeue(void) { if ( isEmpty() ) cout << "Queue is empty" << endl; T ret = first->getData(); Node<T>* tmp = first; first = first->getNext(); count--; delete tmp; return ret; } T First(void) { if (isEmpty()) cout << "Queue is empty" << endl; return first->getData(); } int Size(void) { return count; } bool isEmpty(void) { return count == 0 ? true : false; } };
Node class code:
template <class T> class Node { private: T data; Node* next; public: void setData(T element) { data = element; } void setNext(Node<T>* element) { next = element; } T getData(void) { return data; } Node* getNext(void) { return next; } };
You can download the full project for Visual Studio 2010 from: GenericQueue
Simple y elegante, gracias.