package class5_2_CircularQueue_021; // TODO: Untested code! public class CircularQueue implements Queue { private final int MAX_SIZE = 6; // Smaller value makes testing easier int indFront = 0; // The "front of the line" i.e. first items to come off int indRear = -1; // The "back of the line" i.e. most recently arrived items. E[] array = (E[]) new Object[MAX_SIZE]; @Override public E poll() { if(isEmpty()) { return null; } E result = array[indFront]; indFront++; if(indFront == indRear + 1) { // Queue is again empty! indFront = 0; indRear = -1; } else if(indFront >= array.length) { indFront = 0; } return result; } @Override public boolean offer(E e) { if(isFull()) { return false; } indRear++; if(indRear >= array.length) { indRear = 0; } array[indRear] = e; return true; } @Override public E peek() { if(isEmpty()) { return null; } return array[indFront]; } @Override public boolean isEmpty() { return (indRear < 0); } /** * Returns true if no more elements can be added to the array. * @return true if full */ private boolean isFull() { return ((indRear+1)%array.length == indFront); } }