Advertisement
Guest User

Static queue

a guest
Nov 21st, 2017
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.48 KB | None | 0 0
  1. public class StaticQueue {
  2.  
  3.     private int[] arr;
  4.     private int count;
  5.  
  6.     public StaticQueue() {
  7.         arr = new int[5];
  8.         count = 0;
  9.     }
  10.  
  11.     public void offer(int element) throws Exception {
  12.         add(count, element);
  13.     }
  14.  
  15.     private void add(int index, int element) throws Exception {
  16.         if(index > count || index < 0) {
  17.             throw new Exception();
  18.         }
  19.  
  20.         if(count + 1 == arr.length) {
  21.             int[] extendetArr = new int[arr.length * 2];
  22.             System.arraycopy(arr, 0, extendetArr, 0, arr.length);
  23.             arr = extendetArr;
  24.         }
  25.  
  26.         count++;
  27.         arr[index] = element;
  28.     }
  29.  
  30.     public int poll() {
  31.         if(count > 0) {
  32.             int polledElement = arr[0];
  33.             int[] extendArr = new int[arr.length];
  34.             System.arraycopy(arr, 1, extendArr, 0, arr.length - 1);
  35.             arr = extendArr;
  36.             count--;
  37.             return polledElement;
  38.         } else {
  39.             return -1;
  40.         }
  41.  
  42.     }
  43.  
  44.     public void clear() {
  45.         count = 0;
  46.         this.arr = new int[5];
  47.     }
  48.  
  49.     public boolean contains(int element) {
  50.         for(int i = 0; i < arr.length; i++) {
  51.             if(arr[i] == element) {
  52.                 return true;
  53.             }
  54.         }
  55.         return false;
  56.     }
  57.  
  58.     public int peek() {
  59.         if(count > 0)
  60.             return arr[0];
  61.         return -1;
  62.     }
  63.  
  64.     public int size() {
  65.         return this.count;
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement