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
算法就是:用front 和end分别表示头和尾,最重要的考点就是用size来表示里面有多少个元素。这样 front和rear只需要一直向前走就可以了。
每次enqueue和dequeue的时候,都用size,也就是count来进行判断,这样就省去了用双指针来计算空间的问题。
每次front和end都应该指向下一个,然后需要
front = (front+1)%qeueue.length 和end = (end+1)%qeueue.length一下。
注意: end init值为-1,是为了第一次进去,是从0开始的;
class MyCircularQueue {
public int front;
public int end;
public int size;
public int[] array;
public MyCircularQueue(int k) {
this.array = new int[k];
this.front = 0;
this.end = -1;
this.size = 0;
}
public boolean enQueue(int value) {
if(size < array.length) {
end = (end + 1) % array.length;
array[end] = value;
size++;
return true;
} else {
return false;
}
}
public boolean deQueue() {
if(size > 0) {
front = (front + 1) % array.length;
size--;
return true;
} else {
return false;
}
}
public int Front() {
return size > 0 ? array[front] : -1;
}
public int Rear() {
return size > 0 ? array[end] : -1;
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == array.length;
}
}
/**
* Your MyCircularQueue object will be instantiated and called as such:
* MyCircularQueue obj = new MyCircularQueue(k);
* boolean param_1 = obj.enQueue(value);
* boolean param_2 = obj.deQueue();
* int param_3 = obj.Front();
* int param_4 = obj.Rear();
* boolean param_5 = obj.isEmpty();
* boolean param_6 = obj.isFull();
*/