Design Circular Queue 设计循环队列
Description
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.
Implementation the MyCircularQueue
class:
MyCircularQueue(k)
Initializes the object with the size of the queue to bek
.int Front()
Gets the front item from the queue. If the queue is empty, return-1
.int Rear()
Gets the last item from the queue. If the queue is empty, return-1
.boolean enQueue(int value)
Inserts an element into the circular queue. Returntrue
if the operation is successful.boolean deQueue()
Deletes an element from the circular queue. Returntrue
if the operation is successful.boolean isEmpty()
Checks whether the circular queue is empty or not.boolean isFull()
Checks whether the circular queue is full or not.
设计循环的队列
思路:
使用数组,head为首节点,tail为尾节点后一个节点,cnt为队列元素个数
class MyCircularQueue {
public int head = 0;
public int tail =0 ;
public int cnt =0;
public int[] arr ;
public MyCircularQueue(int k) {
arr = new int[k];
head = 0;
tail =0 ;
cnt =0;
}
public boolean enQueue(int value) {
if(isFull()){
return false;
}
arr[tail] = value;
tail = (tail +1 ) % arr.length;
cnt+=1;
return true;
}
public boolean deQueue() {
if(isEmpty()){
return false;
}
head = (head +1 ) % arr.length;
cnt-=1;
return true;
}
public int Front() {
if(isEmpty()){
return -1;
}
return arr[head];
}
public int Rear() {
if(isEmpty()){
return -1;
}
return arr[(tail-1+arr.length)%arr.length];
}
public boolean isEmpty() {
if(cnt==0){
return true;
}
else{
return false;
}
}
public boolean isFull() {
if(cnt==arr.length){
return true;
}
else{
return false;
}
}
}
/**
* 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();
*/