In C++ Write a generic class, named Queue, in C++ for the queue type that uses a
ID: 3671559 • Letter: I
Question
In C++
Write a generic class, named Queue, in C++ for the queue type that uses a linked list to store the elements. The Queue class has a member variable, named head, that references the first node of the list, a member variable, named tail, that references the last node of the list, and a member variable, named size, that stores the number of elements in the queue. The Queue class provides all of the methods of the STL queue class, including push, pop, front, and empty. The Node class is defined as follows.
template <typename T>
class Node {
public:
T nodeValue;
Node<T> *next;
Node (const T& item, Node<T> *ptr = NULL): nodeValue(item), next(ptr) {}
};
Write a class, named DerivedQueue, which extends Queue by providing a method named
emergency push that inserts an element at the front of the queue.
Explanation / Answer
#include<iostream>
#include<cstdio>
using std::cout;
template <typename T>
class Node{
public:
T nodeValue;
Node<T> *next;
Node (const T& item, Node<T> *ptr = NULL): nodeValue(item), next(ptr) {}
Node(){}
};
template <typename T>
class Queue{
public:
Node<T> *head = NULL;
Node<T> *tail = NULL;
Node<T> *p = NULL;
Node<T> *np = NULL;
void push(T);
T pop();
T Front();
};
template <typename T>
void Queue<T>::push(T x)
{
np = new Node<T>;
np->nodeValue = x;
np->next = NULL;
if(head == NULL)
{
head = tail = np;
tail->next = NULL;
}
else
{
tail->next = np;
tail = np;
tail->next = NULL;
}
}
template <typename T>
T Queue<T>::pop()
{
T x;
if(head == NULL)
{
cout<<"empty queue ";
return NULL; // TODO: find a way to fix: Control may reach end of non-void function
}
if (head==tail)
head = tail = NULL;
else
{
p = head;
x = p->nodeValue;
head = head->next;
delete(p);
return(x);
}
}
template <typename T>
T Front() {
if(head == NULL) {
cout<<"Queue is empty ";
return;
}
return head->nodeValue;
}
template <typename T>
class DerivedQueue : public Queue<T>{
public:
void emergency_push(T x);
};