swoop

1009 tut 2

Mar 9th, 2012
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.32 KB | None | 0 0
  1. package circArray;
  2.  
  3. import java.util.NoSuchElementException;
  4.  
  5. public class CircularArrayQueue implements MyQueue {
  6.  
  7.     private int[] circularArray;
  8.     private int noElements;
  9.     private int head;
  10.     private int tail;
  11.    
  12.     public CircularArrayQueue(){
  13.         circularArray = new int[10];
  14.         noElements = 0;
  15.         head = 0;
  16.         tail = 0;
  17.     }
  18.    
  19.     @Override
  20.     public void enqueue(int in) {
  21.         int n = circularArray.length;
  22.         if(noElements == n){
  23.             increaseArrayCap();
  24.         }
  25.         circularArray[tail] = in;
  26.         noElements++;
  27.         tail++;
  28.         if(tail == n && noElements <= n){
  29.             tail = 0;
  30.         }
  31.     }
  32.  
  33.     @Override
  34.     public int dequeue() throws NoSuchElementException {
  35.         int n = circularArray.length;
  36.         int removed = circularArray[head];
  37.         noElements --;
  38.         head++;
  39.         if(head == n && noElements <= n){
  40.             head = 0;
  41.         }
  42.         return removed;
  43.     }
  44.  
  45.     @Override
  46.     public int noItems() {
  47.         return noElements;
  48.     }
  49.  
  50.     @Override
  51.     public boolean isEmpty() {
  52.         if(noElements == 0){
  53.             return true;
  54.         }
  55.         else{
  56.         return false;
  57.         }
  58.     }
  59.    
  60.     public int getCapacity(){
  61.         int capacity = circularArray.length - noElements;
  62.         return capacity;
  63.     }
  64.  
  65.     private void increaseArrayCap(){
  66.         int n = circularArray.length;
  67.         int[] biggerArray = new int[2*n];
  68.         for(int i = 0; i < n; i++){
  69.             biggerArray[i] = circularArray[i];         
  70.         }
  71.         circularArray = biggerArray;
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment