Advertisement
Aldin-SXR

Queue.java

Mar 5th, 2020
351
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.41 KB | None | 0 0
  1. package ds.queue.regular;
  2.  
  3. public class Queue<Item> { 
  4.     @SuppressWarnings("unchecked")
  5.     private Item[] q = (Item[]) new Object[1];
  6.    
  7.     private int head = 0;
  8.     private int tail = 0;
  9.     private int length = 0;
  10.    
  11.    
  12.     /* Add a new item to the back of the queue */
  13.     public void enqueue(Item item) {
  14.         if (q.length == length) {       // 1
  15.             resize(2 * q.length);       // 1
  16.         }                               // 1
  17.        
  18.         q[tail] = item;                 // 2
  19.         tail = (tail + 1) % q.length;   // 3
  20.         length++;                       // 4
  21.     }
  22.    
  23.     /* Removes an item from the front of the queue, and returns its data */
  24.     public Item dequeue() {
  25.         Item item = q[head];                            // 1
  26.         q[head] = null;                                 // 2
  27.         head = (head + 1) % q.length;                   // 3
  28.        
  29.         if (length > 0 && length == q.length / 4) {     // 4
  30.             resize(q.length / 2);                       // 4
  31.         }                                               // 4
  32.        
  33.         length--;                                       // 5
  34.         return item;                                    // 6
  35.     }
  36.    
  37.     /* Create a new internal array with a given capacity */
  38.     @SuppressWarnings("unchecked")
  39.     public void resize(int capacity) {
  40.         Item[] copy = (Item[]) new Object[capacity];    // 1
  41.         for (int i = 0; i < length; i++) {              // 2
  42.             copy[i] = q[(i + head) % q.length];         // 2
  43.         }                                               // 2
  44.         head = 0;                                       // 3
  45.         tail = length;                                  // 3
  46.         q = copy;                                       // 4
  47.     }
  48.    
  49.     /* Check if the queue is empty */
  50.     public boolean isEmpty() {
  51.         return length == 0;
  52.     }
  53.    
  54.     /* Return the current size of the queue */
  55.     public int size() {
  56.         return length;
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement