Below is a problem from Sedgewick's Algorithms and my solution. Any thoughts or suggestions for improvement would be much appreciated.
Develop a class that implements the queue abstraction with a fixed-sized array, and then extend your implementation to use array resizing.
package chapter_1_3_bagsQueuesStacks;
import java.util.Arrays;
import java.util.Iterator;
// Exercise 1.3.14 | pg. 163
public class ArrayQueue<E> implements Iterable<E> {
private E[] a = (E[]) new Object[1];
private int head;
private int tail;
private int N;
public boolean isEmpty() {
return N == 0;
}
private boolean isFull() {
return N == a.length;
}
public int size() {
return N;
}
private void resize(int cap) {
E[] temp = (E[]) new Object[cap];
int curr = head;
for (int i = 0; i < N; i++) {
temp[i] = a[curr];
if (curr == a.length-1) {
curr = 0;
} else {
curr++;
}
}
a = temp;
}
public void enqueue(E element) {
if (isFull()) {
resize(a.length*2);
head = 0;
tail = N-1;
}
if (isEmpty()) {
head = tail = 0;
} else if (tail == a.length-1) {
tail = 0;
} else {
tail++;
}
a[tail] = element;
N++;
}
public E dequeue() {
if (isEmpty())
throw new RuntimeException();
E element = a[head];
a[head] = null;
N--;
if (head == a.length-1) {
head = 0;
} else {
head++;
}
if (N == a.length/4) {
resize(a.length/2);
head = 0;
tail = N-1;
}
return element;
}
@Override
public Iterator<E> iterator() {
return new ArrayIterator();
}
private class ArrayIterator implements Iterator<E> {
int curr = head;
@Override
public boolean hasNext() {
return a[curr] != null;
}
@Override
public E next() {
E element = a[curr++];
return element;
}
}
@Override
public String toString() {
String formatStr = "HEAD: %s - TAIL: %s - %s";
return String.format(formatStr, this.head, this.tail, Arrays.toString(this.a));
}
}