In: Computer Science
(Implement GenericQueue using inheritance) In Section 24.5, Stacks and Queues, GenericQueue is implemented using composition. Define a new queue class that extends java.util.LinkedList..
GenericQueue.java
import java.util.LinkedList;
public class GenericQueue<E> extends
LinkedList<E>
{
/**
*
*/
private static final long serialVersionUID = 1L;
E head;
E tail;
public GenericQueue()
{
head = null;
tail = null;
}
public boolean isEmpty()
{
if(size() == 0)
return
true;
return false;
}
public void enqueue(E c)
{
add(c);
// if the list was initially empty point both head and
tail to element
if(head == null && tail == null)
{
head = c;
tail = c;
}
else
{
//only change tail and point it to
recently added node
tail = c;
}
}
public E dequeue()
{
if(isEmpty())
return null;
E firstElement = getFirst(); // getLast is a
linkedList method;
poll(); // this removes the element at the head
if(isEmpty()) // if there was a single element in the
list, point both head and tail to null
{
head = null;
tail = null;
}
else
head = getFirst(); // point the
head to the current first node. No change in tail
return firstElement; // return the element we just removed from the
queue
}
//return the first element of queue without removing it
public E peek()
{
return (E) element(); // this is a linkedlist method
which retrieves but does not remove the head of the queue
}
public void print()
{
System.out.print("PrintList: ");
Object[] ab = toArray(); //toArray is a linkedlist
method that returns all elemnts of list in array from head to tail
sequence
for(int i=0; i<size(); i++)
{
System.out.print(ab[i] + "
");
}
System.out.println();
}
}
GenericQueueDemo.java
public class GenericQueueDemo
{
public static void main(String args[])
{
GenericQueue<Integer> g1 =
new GenericQueue<Integer>();
System.out.println("Is queue empty?
"+ g1.isEmpty());
g1.enqueue(5);
g1.print();
g1.enqueue(6);
g1.enqueue(45);
System.out.println("Peek: "+
g1.peek());
g1.print();
System.out.println("Is queue empty?
"+ g1.isEmpty());
g1.dequeue();
System.out.println("Peek: "+
g1.peek());
g1.print();
GenericQueue<String> g2 = new
GenericQueue<String>();
System.out.println("Is queue empty?
"+ g1.isEmpty());
g2.enqueue("Hello");
g2.enqueue("World!");
g2.enqueue("This");
g2.enqueue("is");
g2.enqueue("a");
g2.enqueue("new");
g2.enqueue("day");
g2.print();
g2.enqueue("Welcome");
g2.enqueue("back!!");
System.out.println("Peek: "+
g2.peek());
g2.print();
System.out.println("Is queue empty?
"+ g1.isEmpty());
g2.dequeue();
System.out.println("Peek: "+
g2.peek());
g2.print();
g2.dequeue();
g2.print();
g2.dequeue();
g2.print();
}
}
Sample I/O and output