Advertisement
Guest User

Untitled

a guest
Feb 25th, 2020
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.12 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. public class ArrayQueue {
  4.     private int length = 5;
  5.     private Object[] queue = new Object[length];
  6.     private int head = 0;
  7.     private int tail = 0;
  8.  
  9.     public void enqueue(Object x) {
  10.         ensureCapacity(size() + 1);
  11.         queue[tail] = x;
  12.         tail = (tail + 1) % length;
  13.     }
  14.  
  15.     private void ensureCapacity(int capacity) {
  16.         if (capacity > length) {
  17.             length *= 2;
  18.             queue = Arrays.copyOf(queue, length);
  19.         }
  20.     }
  21.  
  22.     public Object element() {
  23.         assert size() != 0;
  24.  
  25.         return queue[head];
  26.     }
  27.  
  28.  
  29.     public Object dequeue() {
  30.         if (isEmpty()) {
  31.             return null;
  32.         }
  33.         Object x = queue[head];
  34.         head = (head + 1) % length;
  35.         return x;
  36.     }
  37.  
  38.     public int size() {
  39.         if (head > tail) {
  40.             return length - head + tail;
  41.         } else {
  42.             return tail - head;
  43.         }
  44.     }
  45.  
  46.     public boolean isEmpty() {
  47.         return head == tail;
  48.     }
  49.  
  50.     public void clear() {
  51.         queue = new Object[5];
  52.         head = 0;
  53.         tail = 0;
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement