/* This is an implementation of a queue that uses a circularly linked list. A pointer is maintained that points to the rear of the queue. That node in turn points to the front of the queue. In this way, both the front and rear of the queue are accessible without having to travel through the entire list. */
package Queue;
// A class to define a node in the queue.
public class QueueNode
{
protected String ID;
protected QueueNode next;
protected QueueNode getNext () {return next;}
protected void setNext (QueueNode newNode)
{ next = newNode;}
public String getID () {return ID;}
public void setID (String newID) {ID = newID;}
} // class QueueNode
package Queue;
// An interface that defines the methods for the queue.
public interface QueueInterface
{
public boolean empty ();
public void addToRear (QueueNode newNode);
public QueueNode deleteFromFront ();
} // QueueInterface
package Queue;
import java.io.*;
// A class with methods to add to the queue, delete from the queue
and test for empty.
public class QueueClass implements QueueInterface
{
protected QueueNode queueRear = null;
public boolean empty ()
{
if (queueRear == null) return true;
else return false;
} // method empty
public void addToRear (QueueNode newNode)
{
if (queueRear == null)
{
queueRear = newNode;
newNode.setNext (newNode);
}
else
{
newNode.setNext (queueRear.getNext ());
queueRear.setNext (newNode);
queueRear = newNode;
}
} // method addToRear
public QueueNode deleteFromFront
()
{
if (queueRear == null)
{
System.out.println ("Error - empty queue");
return null;
}
else
{
QueueNode tempNode = queueRear.getNext ();
if (queueRear.getNext () == queueRear) queueRear = null;
else queueRear.setNext (tempNode.getNext ());
return tempNode;
}
} // method deleteFromFront
} // class QueueClass
/* A class to test the queue methods defined in QueueClass
import java.io.*;
import Queue.QueueNode;
import Queue.QueueClass;
public class TestQueue
{
public static void main (String [] args)
{
QueueClass queue
= new QueueClass ();
QueueNode tempNode;
for (int count
= 0; count < 5; count ++)
{
tempNode = new QueueNode ();
tempNode.setID ("" + count);
queue.addToRear (tempNode);
}
System.out.println
("Queue contents");
while (!queue.empty
())
{
tempNode = queue.deleteFromFront ();
System.out.println (tempNode.getID ());
}
} // method main
} // class TestQueue