WallHero

TP03E02CircularQueue

Oct 16th, 2020 (edited)
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.32 KB | None | 0 0
  1. import java.util.NoSuchElementException;
  2.  
  3. public class CircularQueue<ELEMENT> {
  4.    
  5.     private ELEMENT[] queue;
  6.     private int size, front, last, nElements;
  7.    
  8.     @SuppressWarnings("unchecked")
  9.     public CircularQueue(int size)
  10.     {
  11.         this.size = size;
  12.         this.front = this.last = -1;
  13.         this.queue = (ELEMENT[]) new Object[size];
  14.         this.nElements = 0;
  15.     }
  16.    
  17.     public ELEMENT getFront() {
  18.         if(isEmpty()) return null;
  19.         return queue[front];
  20.     }
  21.    
  22.     public ELEMENT getLast() {
  23.         if(isEmpty()) return null;
  24.         return queue[last-1];
  25.     }
  26.    
  27.     public ELEMENT[] getQueueArray()
  28.     {
  29.         return this.queue;
  30.     }
  31.     public int getSize()
  32.     {
  33.         return this.size;
  34.     }
  35.     public boolean isEmpty() {
  36.         return this.nElements == 0;
  37.     }
  38.    
  39.     public boolean isFull()
  40.     {
  41.         return this.nElements == this.size;
  42.     }
  43.    
  44.     public void enqueue(ELEMENT element)
  45.     {
  46.         if(isFull()) throw new IllegalStateException("Queue is full");
  47.         if(element == null) throw new NullPointerException("The new is null!");
  48.         else
  49.         {
  50.            
  51.             if(isEmpty())
  52.             {
  53.                 front = last = 0;
  54.             }
  55.             last%=nElements+1;
  56.             queue[last++] = element;
  57.             nElements++;           
  58.         }
  59.     }
  60.    
  61.     public ELEMENT dequeue()
  62.     {
  63.         if(isEmpty()) throw new NoSuchElementException("Empty queue.");
  64.         ELEMENT retElement = queue[front];
  65.         queue[front++] = null;
  66.         nElements--;
  67.         return retElement;
  68.     }
  69.    
  70. }
  71.  
Add Comment
Please, Sign In to add comment