Advertisement
Guest User

Untitled

a guest
Mar 27th, 2015
258
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.01 KB | None | 0 0
  1.  
  2. class Queue<T> {
  3.  
  4.     private Array<T> _arr;          //backing array
  5.     private int queueStart = 0;     //start of queue; first to be enqueued, first to be dequeued
  6.     private int queueEnd = 0;       //end of queue; most recent enqueue, last to be dequeued
  7.     private int arraySize = 255;    //size of array, only powers of 2
  8.     private int numOfElements = 0;  //counts elements in array
  9.  
  10.     Queue() {
  11.         _arr = new Array<T>(256);   //default, makes backing array of 255 T objects
  12.     }
  13.  
  14.     Queue(int sz) {
  15.         arraySize = MathUtils.nextPowerOfTwo(sz) - 1;   //makes size next power of two after specified size - 1
  16.         _arr = new Array<T>(arraySize);
  17.     }
  18.  
  19.     Queue(Array<T> array) {
  20.         arraySize = MathUtils.nextPowerOfTwo(array.size) - 1;   //makes that can hold provided one with size of next power of two - 1
  21.         _arr = new Array<T>(arraySize);
  22.         Array.ArrayIterator<T> iter = new Array.ArrayIterator<T>(array);
  23.         while (iter.hasNext()) {
  24.             enqueue(iter.next());   //fill queue with array's objects
  25.         }
  26.     }
  27.  
  28.     public void enqueue(T o) {
  29.         if (numOfElements == arraySize - 1) {   // reallocates and refills array if full
  30.             arraySize = MathUtils.nextPowerOfTwo(arraySize + 2);
  31.             Array<T> tempArray = new Array<T>(--arraySize);
  32.             queueStart = 0;
  33.             queueEnd = 0;
  34.             while (!isEmpty()) {
  35.                 tempArray.set(queueEnd++, dequeue());
  36.             }
  37.             _arr = tempArray;
  38.         }
  39.         _arr.set(queueEnd++, o);
  40.         ++numOfElements;
  41.     }
  42.  
  43.     public T dequeue() {
  44.         T value = null;
  45.         if (!isEmpty()) {
  46.             --numOfElements;
  47.             value = _arr.get(queueStart++);
  48.             if (queueStart == arraySize) {
  49.                 queueStart = 0;
  50.             }
  51.         }
  52.         return value;
  53.     }
  54.  
  55.     public int size() {
  56.         return numOfElements;
  57.     }
  58.  
  59.     public boolean isEmpty() {
  60.         return numOfElements == 0;
  61.     }
  62.  
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement