7. Queue (FIFO)
Conceptual View
enqueue
: inserting a new item to the back of the queue
dequeue
: removing the first item from the queue
Queue Implementation using Array
public interface QueueInterface<AnyType> {
void enqueue(AnyType item);
AnyType dequeue();
AnyType peekFront();
boolean isEmpty();
}
public class ArrayQueue<AnyType> implements QueueInterface<AnyType> {
private static final int DEFAULT_CAPACITY = 6;
private Object[] elements;
private int front;
private int back;
private int nItems;
public ArrayQueue() {
elements = new Object[DEFAULT_CAPACITY];
front = 0;
back = -1;
nItems = 0;
}
...
}
Queue Implementation using Array
isEmpty
@Override
public boolean isEmpty() {
return nItems == 0;
}
isFull
private boolean isFull() {
return nItems == elements.length;
}
enqueue
@Override
public void enqueue(AnyType item) {
if (isFull()) {
throw new RuntimeException("Queue is full");
}
back++;
int index = back % elements.length;
elements[index] = item;
nItems++;
}
dequeue
@Override
public AnyType dequeue() {
if (isEmpty()) {
throw new NoSuchElementException();
}
int index = front % elements.length;
@SuppressWarnings("unchecked")
AnyType item = (AnyType) elements[index];
elements[index] = null;
front++;
nItems--;
return item;
}
peekFront
@SuppressWarnings("unchecked")
@Override
public AnyType peekFront() {
if (isEmpty()) {
throw new NoSuchElementException();
}
return (AnyType) elements[front % elements.length];
}
Queue Implementation using LinkedList
LinkedList<Integer> theQueue = new LinkedList<Integer>();
theQueue.addLast(5);
theQueue.removeFirst();
Back to Home
Next Lecture