-
Notifications
You must be signed in to change notification settings - Fork 115
/
Copy pathArrayQueue.java
50 lines (42 loc) Β· 1.05 KB
/
ArrayQueue.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package Queue;
public class ArrayQueue<E> implements IQueue<E> {
private static final int CAPACITY = 1000;
private E[] data;
private int front = 0;
private int size = 0;
public ArrayQueue() {
this(CAPACITY);
}
public ArrayQueue(int capacity) {
data = (E[]) new Object[capacity];
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public void enqueue(E e) {
if (size == data.length) throw new IllegalStateException("Queue is full");
int avail = (front + size) % data.length;
data[avail] = e;
size ++;
}
@Override
public E dequeue() {
if (isEmpty()) return null;
E target = data[front];
data[front] = null; // dereference to help garbage collection
front = (front + 1) % data.length;
size --;
return target;
}
@Override
public E peek() {
if (isEmpty()) return null;
return data[front];
}
}