ArrayCircularQueue.
java
public class ArrayCircularQueue implements Queue {
private int front = 0, rear = 0;
private Object [] queue;
public ArrayCircularQueue (int maxElements) {
queue = new Object [maxElements];
}
public void insert (Object o) {
int temp = rear;
rear = (rear + 1) % [Link];
if (front == rear) {
rear = temp;
throw new FullQueueException ();
}
queue [rear] = o;
}
public boolean isEmpty () {
return front == rear;
}
public boolean isFull () {
return ((rear + 1) % [Link]) == front;
}
public Object remove () {
if (front == rear)
throw new EmptyQueueException ();
front = (front + 1) % [Link];
return queue [front];
}
}
[Link]
public class ArrayLinearQueue implements Queue {
private int front = -1, rear = -1;
private Object [] queue;
public ArrayLinearQueue (int maxElements) {
queue = new Object [maxElements];
}
public void insert (Object o) {
if (rear == [Link] - 1)
throw new FullQueueException ();
queue [++rear] = o;
}
public boolean isEmpty () {
return front == rear;
}
public boolean isFull () {
return rear == [Link] - 1;
}
public Object remove () {
if (front == rear)
throw new EmptyQueueException ();
return queue [++front];
}
}
[Link]
public interface Queue {
void insert (Object o);
boolean isEmpty ();
boolean isFull ();
Object remove ();
}
QueueDemo
class QueueDemo {
public static void main (String [] args) {
[Link] ("ArrayLinearQueue Demo");
[Link] ("---------------------");
queueDemo (new ArrayLinearQueue (5));
[Link] ("ArrayCircularQueue Demo");
[Link] ("---------------------");
queueDemo (new ArrayCircularQueue (6)); // Need one more slot because
// of empty slot in circular
// implementation
}
static void queueDemo (Queue q) {
[Link] ("Is empty = " + [Link] ());
[Link] ("Is full = " + [Link] ());
[Link] ("Inserting \"This\"");
[Link] ("This");
[Link] ("Inserting \"is\"");
[Link] ("is");
[Link] ("Inserting \"a\"");
[Link] ("a");
[Link] ("Inserting \"sentence\"");
[Link] ("sentence");
[Link] ("Inserting \".\"");
[Link] (".");
try {
[Link] ("Inserting \"One last item\"");
[Link] ("One last item");
}
catch (FullQueueException e) {
[Link] ("One insert too many");
[Link] ("Is empty = " + [Link] ());
[Link] ("Is full = " + [Link] ());
}
[Link] ();
while (![Link] ())
[Link] ([Link] () + " [Is empty = " + [Link] () +
", Is full = " + [Link] () + "]");
try {
[Link] ();
}
catch (EmptyQueueException e) {
[Link] ("One remove too many");
}
[Link] ();
}
}