SHARE
TWEET

Untitled

SandroA May 29th, 2020 (edited) 710 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.lang.Math;
  2.  
  3. public class MyDeque<T> {
  4.  
  5.     T[] content;
  6.     int head = -1;
  7.     int tail = -1;
  8.    
  9.     @SuppressWarnings("unchecked")
  10.     public MyDeque(int cap) {
  11.         content = (T[]) new Object[cap];
  12.     }
  13.    
  14.     public boolean isEmpty() {
  15.         if(head == -1 && tail == -1) {
  16.             return true;
  17.         }
  18.         return false;
  19.     }
  20.    
  21.     public boolean isFull() {
  22.         int dif = (head % content.length) - (tail % content.length);
  23.         if(Math.abs(dif) > 1) return false;
  24.         return true;
  25.     }
  26.    
  27.     public int capacity() {
  28.         return content.length;
  29.     }
  30.    
  31.     public int size() {
  32.         if(head > tail) return content.length - head + tail + 1;
  33.         return tail - head + 1;
  34.     }
  35.    
  36.     public T get(int i) {
  37.         return content[(i + head) % content.length];
  38.     }
  39.    
  40.     public void addFirst(T elem) {
  41.         head = (head > 0 ? (head - 1) % content.length : 0);
  42.         if(tail < 0) tail = head;
  43.         content[head] = elem;
  44.     }
  45.    
  46.     public T getFirst() {
  47.         return content[head];
  48.     }
  49.    
  50.     public T removeFirst() {
  51.         int tmpHead = head;
  52.         int newHeadRaw = head + 1;
  53.         head = newHeadRaw % content.length;
  54.         if(tmpHead == tail) {
  55.             if(newHeadRaw > tail) {
  56.                 head = -1;
  57.                 tail = -1;
  58.             }
  59.         }
  60.         return content[tmpHead];
  61.     }
  62.    
  63.     public void addLast(T elem) {
  64.         tail = (tail > 0 ? (tail + 1) % content.length : 0);
  65.         if(head < 0) head = tail;
  66.         content[tail] = elem;
  67.     }
  68.    
  69.     public T removeLast() {
  70.         int tmpTail = tail;
  71.         int newTailRaw = tail - 1;
  72.         tail = newTailRaw % content.length;
  73.         if(tmpTail == head) {
  74.             if(newTailRaw < head) {
  75.                 head = -1;
  76.                 tail = -1;
  77.             }
  78.         }
  79.         return content[tmpTail];
  80.     }
  81.    
  82.     public String toString() {
  83.         return "Head: " + content[head] + "; Tail: " + content[tail] + "; Size: " + size();
  84.     }
  85. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top