Monday, March 20, 2017

Design a Queue using Array with certain Capacity

public class ArrayQueue<E> {
private int head;
private int tail;
private int size;
private E[] array;
private final int CAPACITY = 10;
public ArrayQueue<E>(int capacity) {
this.array = new E[capacity];
this.head = 0;
this.tail =  0;
this.size = 0;
}

public ArrayQueue<E>() {
this(CAPACITY);
}
public boolean offer(E element) {
if (this.size >= array.length) return false;
array[tail] = element;
tail = (tail + 1) % array.length; // very important
size++;
return true;
}
public E poll() {
if (this.size == 0) return null;
E temp = array[head];
head = (head + 1) % array.length;
size--;
return temp;
}
public E peek() {
return size == 0 ? null : array[head];
}
}

No comments:

Post a Comment