Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer".
One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.
Your implementation should support following operations:
MyCircularQueue(k)
: Constructor, set the size of the queue to be k.Front
: Get the front item from the queue. If the queue is empty, return -1.Rear
: Get the last item from the queue. If the queue is empty, return -1.enQueue(value)
: Insert an element into the circular queue. Return true if the operation is successful.deQueue()
: Delete an element from the circular queue. Return true if the operation is successful.isEmpty()
: Checks whether the circular queue is empty or not.isFull()
: Checks whether the circular queue is full or not.
Example:
MyCircularQueue circularQueue = new MyCircularQueue(3); // set the size to be 3 circularQueue.enQueue(1); // return true circularQueue.enQueue(2); // return true circularQueue.enQueue(3); // return true circularQueue.enQueue(4); // return false, the queue is full circularQueue.Rear(); // return 3 circularQueue.isFull(); // return true circularQueue.deQueue(); // return true circularQueue.enQueue(4); // return true circularQueue.Rear(); // return 4
1 class MyCircularQueue { 2 final int[] a; 3 int front, rear = -1, len = 0; 4 5 public MyCircularQueue(int k) { 6 a = new int[k]; 7 } 8 9 public boolean enQueue(int val) { 10 if (!isFull()) { 11 rear = (rear + 1) % a.length; 12 a[rear] = val; 13 len++; 14 return true; 15 } else { 16 return false; 17 } 18 } 19 20 public boolean deQueue() { 21 if (!isEmpty()) { 22 front = (front + 1) % a.length; 23 len--; 24 return true; 25 } else 26 return false; 27 } 28 29 public int Front() { 30 return isEmpty() ? -1 : a[front]; 31 } 32 33 public int Rear() { 34 return isEmpty() ? -1 : a[rear]; 35 } 36 37 public boolean isEmpty() { 38 return len == 0; 39 } 40 41 public boolean isFull() { 42 return len == a.length; 43 } 44 }