IN JAVA Write a generic class, named Queue, in Java for the queue type that uses
ID: 3678062 • Letter: I
Question
IN JAVA
Write a generic class, named Queue, in Java 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 the following methods: push, pop, front, and empty. The Node class is defined as follows.
1
class Node<T> {
public T nodeValue;
public Node<T> next;
Node(T item){
this(item, null);
}
Node(T item, Node<T> next){
nodeValue = item;
this.next = next;
}
}
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
public class Queue<T> {
//Construct queue.
public Queue(){
head = tail = new Node<T>(null);
size = 0;
};
//Test whether container is empty.
public boolean empty(){
return size == 0;
};
//Return size.
public int size(){
return size;
};
//Access next element.
public T front(){
if(!empty())
return head.nodeValue;
else return null;
}
//Access last element.
public T back(){
if(!empty())
return tail.nodeValue;
else return null;
}
//Insert element.
public void push(final T item){
Node<T> n = new Node<T>(item);
if(empty())
head = tail = n;
else if(size() == 1){
head.next = n;
tail = n;
}
else{
Node<T> temp = tail;
tail = n;
temp.next = n;
}
size++;
};
//Remove next element.
public void pop(){
if(empty()){
System.out.println("No elements to pop.");
return;
}
else if(size() == 1){
head = tail = new Node<T>(null);
}
else head = head.next;
size --;
};
//Print all elements of queue.
public void printQueue(){
if(empty()){
System.out.println("Queue is empty, no elements to print.");
return;
}
Node<T> n = head;
while(n != null){
System.out.print(n.nodeValue + " ");
n = n.next;
}
System.out.println();
};
protected int size;
protected Node<T> head;
protected Node<T> tail;
}
public class DerivedQueue<T> extends Queue<T>{
public void emergency_push(T item){
if(empty()) push(item);
else {
Node<T> n = new Node<T>(item);
Node<T> temp = head;
head = n;
head.next = temp;
}
size++;
}
}