Skip to content

Instantly share code, notes, and snippets.

@tomwhoiscontrary
Created October 15, 2012 17:04
Show Gist options
  • Save tomwhoiscontrary/3893650 to your computer and use it in GitHub Desktop.
Save tomwhoiscontrary/3893650 to your computer and use it in GitHub Desktop.
public class CircularQueue<T> {
private T[] queue = newArray(5);
private int front = 0;
private int rear = 0;
public void enqueue(T element) {
if (front == (rear + 1) % queue.length) {
expandCapacity();
}
queue[rear] = element;
rear = (rear + 1) % queue.length;
}
public void expandCapacity() {
T[] larger = newArray(queue.length * 2);
for (int scan = 0; scan < queue.length; scan++) {
larger[scan] = queue[front];
front = (front + 1) % queue.length;
}
front = 0;
rear = queue.length - 1;
queue = larger;
}
private static <T> T[] newArray(int length) {
@SuppressWarnings("unchecked")
T[] larger = ((T[]) (new Object[length]));
return larger;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < queue.length; i++) {
T element = queue[i];
sb.append(i == front ? ">" : " ");
sb.append(element != null ? element : " ");
sb.append(i == rear ? "<" : " ");
sb.append("|");
}
sb.setLength(sb.length() - 3);
sb.append("]");
if (rear == queue.length - 1) sb.append("<");
return sb.toString();
}
public static void main(String[] args) {
CircularQueue<Integer> cq = new CircularQueue<Integer>();
System.out.println(cq);
for (int i = 0; i < 10; i++) {
cq.enqueue(i);
System.out.println(cq);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment