// Bare-bones, array-based implementation of a fixed-capacity queue // in the style of Sedgwick & Wayne fixed-capacity stack (p. 135). // // front is the index of the first element in the queue. // back is the index of the first free element after the end of the queue. // (front == back) is defined to be an empty queue. // public class FixedCapacityQueue { private Item [] a; private int capacity; private int front; private int back; public FixedCapacityQueue(int cap) { a = (Item[]) new Object[cap]; front = back = 0; // not strictly necessary: java initializes instance variables to zero capacity = cap; } public boolean isEmpty() { return front == back; } public int size() { if (back >= front) return back - front; else return capacity - (back - front); // wraparound case } public void enqueue(Item item) { a[back] = item; back = (back + 1) % capacity; // handles wraparound } public Item dequeue() { Item d = a[front]; a[front] = null; // Avoid loitering front = (front + 1) % capacity; // handles wraparound return d; } }