EPI Solution:
https://github.com/epibook/epibook.github.io/blob/master/solutions/java/src/main/java/com/epi/CircularQueueTemplate.java
public static class Queue<T> {
private int head = 0, tail = 0, count = 0;
private Object[] data;
public Queue(int cap) {
data = new Object[cap];
}
public void enqueue(T x) {
// Dynamically resize due to data_.size() limit.
if (count == data.length) {
// Rearrange elements.
Collections.rotate(Arrays.asList(data), -head);
head = 0;
tail = count;
data = Arrays.copyOf(data, count << 1);
}
// Perform enqueue
data[tail] = x;
tail = (tail + 1) % data.length;
++count;
}
public T dequeue() {
if (count != 0) {
--count;
T ret = (T) data[head];
head = (head + 1) % data.length;
return ret;
}
throw new RuntimeException("empty queue");
}
public int size() {
return count;
}
}
http://oppansource.com/queue-implementation-in-java-using-circular-array/
http://www.java2s.com/Code/Java/Collections-Data-Structure/CircularQueue.htm
https://github.com/epibook/epibook.github.io/blob/master/solutions/java/src/main/java/com/epi/CircularQueueTemplate.java
public static class Queue<T> {
private int head = 0, tail = 0, count = 0;
private Object[] data;
public Queue(int cap) {
data = new Object[cap];
}
public void enqueue(T x) {
// Dynamically resize due to data_.size() limit.
if (count == data.length) {
// Rearrange elements.
Collections.rotate(Arrays.asList(data), -head);
head = 0;
tail = count;
data = Arrays.copyOf(data, count << 1);
}
// Perform enqueue
data[tail] = x;
tail = (tail + 1) % data.length;
++count;
}
public T dequeue() {
if (count != 0) {
--count;
T ret = (T) data[head];
head = (head + 1) % data.length;
return ret;
}
throw new RuntimeException("empty queue");
}
public int size() {
return count;
}
}
http://oppansource.com/queue-implementation-in-java-using-circular-array/
http://www.java2s.com/Code/Java/Collections-Data-Structure/CircularQueue.htm