Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- public class ArrayQueue {
- private int length = 5;
- private Object[] queue = new Object[length];
- private int head = 0;
- private int tail = 0;
- public void enqueue(Object x) {
- ensureCapacity(size() + 1);
- queue[tail] = x;
- tail = (tail + 1) % length;
- }
- private void ensureCapacity(int capacity) {
- if (capacity > length) {
- length *= 2;
- queue = Arrays.copyOf(queue, length);
- }
- }
- public Object element() {
- assert size() != 0;
- return queue[head];
- }
- public Object dequeue() {
- if (isEmpty()) {
- return null;
- }
- Object x = queue[head];
- head = (head + 1) % length;
- return x;
- }
- public int size() {
- if (head > tail) {
- return length - head + tail;
- } else {
- return tail - head;
- }
- }
- public boolean isEmpty() {
- return head == tail;
- }
- public void clear() {
- queue = new Object[5];
- head = 0;
- tail = 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement