Advertisement
daniel_079

ArrayQueueModule

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