Advertisement
korobushk

cQ

May 23rd, 2021
823
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.06 KB | None | 0 0
  1. class MyCircularQueue {
  2.    
  3.     private int[] data;
  4.     private int head;
  5.     private int tail;
  6.     private int size;
  7.  
  8.     /** Initialize your data structure here. Set the size of the queue to be k. */
  9.     public MyCircularQueue(int k) {
  10.         data = new int[k];
  11.         head = -1;
  12.         tail = -1;
  13.         size = k;
  14.     }
  15.    
  16.     /** Insert an element into the circular queue. Return true if the operation is successful. */
  17.     public boolean enQueue(int value) {
  18.         if (isFull() == true) {
  19.             return false;
  20.         }
  21.         if (isEmpty() == true) {
  22.             head = 0;
  23.         }
  24.         tail = (tail + 1) % size;
  25.         data[tail] = value;
  26.         return true;
  27.     }
  28.    
  29.     /** Delete an element from the circular queue. Return true if the operation is successful. */
  30.     public boolean deQueue() {
  31.         if (isEmpty() == true) {
  32.             return false;
  33.         }
  34.         if (head == tail) {
  35.             head = -1;
  36.             tail = -1;
  37.             return true;
  38.         }
  39.         head = (head + 1) % size;
  40.         return true;
  41.     }
  42.    
  43.     /** Get the front item from the queue. */
  44.     public int Front() {
  45.         if (isEmpty() == true) {
  46.             return -1;
  47.         }
  48.         return data[head];
  49.     }
  50.    
  51.     /** Get the last item from the queue. */
  52.     public int Rear() {
  53.         if (isEmpty() == true) {
  54.             return -1;
  55.         }
  56.         return data[tail];
  57.     }
  58.    
  59.     /** Checks whether the circular queue is empty or not. */
  60.     public boolean isEmpty() {
  61.         return head == -1;
  62.     }
  63.    
  64.     /** Checks whether the circular queue is full or not. */
  65.     public boolean isFull() {
  66.         return ((tail + 1) % size) == head;
  67.     }
  68. }
  69.  
  70. /**
  71.  * Your MyCircularQueue object will be instantiated and called as such:
  72.  * MyCircularQueue obj = new MyCircularQueue(k);
  73.  * boolean param_1 = obj.enQueue(value);
  74.  * boolean param_2 = obj.deQueue();
  75.  * int param_3 = obj.Front();
  76.  * int param_4 = obj.Rear();
  77.  * boolean param_5 = obj.isEmpty();
  78.  * boolean param_6 = obj.isFull();
  79.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement