Advertisement
Guest User

Untitled

a guest
Mar 9th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.29 KB | None | 0 0
  1. import java.util.NoSuchElementException;
  2.  
  3. public class CircularArrayQueue implements MyQueue {
  4.  
  5.     private Integer[] array;
  6.     private int noItems, tail, head;
  7.  
  8.     public CircularArrayQueue() {
  9.         array = new Integer[10];
  10.         noItems = 0;
  11.         tail = 0;
  12.         head = 0;
  13.     }
  14.  
  15.     public int getCapacityLeft() {
  16.         return array.length - noItems;
  17.     }
  18.  
  19.     public void enqueue(int n) {
  20.         if (noItems == array.length)
  21.             resize();
  22.  
  23.         array[tail] = n;
  24.         tail = (tail + 1) % array.length;
  25.         noItems++;
  26.     }
  27.  
  28.     public int dequeue() throws NoSuchElementException {
  29.         if (isEmpty())
  30.             throw new NoSuchElementException();
  31.  
  32.         Integer deq = array[head];
  33.         array[head] = null;
  34.  
  35.         head = (head + 1) % array.length;
  36.         noItems--;
  37.         return deq;
  38.     }
  39.  
  40.     public int noItems() {
  41.         return this.noItems;
  42.     }
  43.  
  44.     public boolean isEmpty(){
  45.         return (noItems == 0);
  46.     }
  47.  
  48.     public void resize() {
  49.         Integer[] resizedArray = new Integer[array.length * 2];
  50.  
  51.         for (int i = 0; i < noItems; i++) {
  52.             resizedArray[i] = array[(head + i) % array.length];
  53.         }
  54.  
  55.         array = resizedArray;
  56.         head = 0;
  57.         tail = noItems;
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement