class MyCircularQueue { private int head; private int tail; private int size; private int currentSize; int[] queue; //顺序队列 /** Initialize your data structure here. Set the size of the queue to be k. */ public MyCircularQueue(int k) { this.size = k; queue = new int[size]; head = 0; tail = 0; currentSize = 0; } /** Insert an element into the circular queue. Return true if the operation is successful. */ public boolean enQueue(int value) { if(currentSize == size){ return false; } if(currentSize == 0){ head = (head+1)%size; } tail = (tail+1)%size; queue[tail] = value; currentSize++; return true; } /** Delete an element from the circular queue. Return true if the operation is successful. */ public boolean deQueue() { if(currentSize == 0){ return false; } currentSize--; if(currentSize != 0){ head = (head + 1)%size; } return true; } /** Get the front item from the queue. */ public int Front() { if(currentSize == 0){ return -1; } return queue[head]; } /** Get the last item from the queue. */ public int Rear() { if(currentSize== 0){ return -1; } return queue[tail]; } /** Checks whether the circular queue is empty or not. */ public boolean isEmpty() { if(currentSize == 0){ return true; } return false; } /** Checks whether the circular queue is full or not. */ public boolean isFull() { if(currentSize == size){ return true; } return false; } }
class MyCircularQueue { private Integer[] queue; private int head; private int tail; /** Initialize your data structure here. Set the size of the queue to be k. */ public MyCircularQueue(int k) { queue = new Integer[k]; head = 0; tail = 0; } /** Insert an element into the circular queue. Return true if the operation is successful. */ public boolean enQueue(int value) { if(isFull()){ return false; } queue[tail] = value; tail = (tail + 1) % queue.length; return true; } /** Delete an element from the circular queue. Return true if the operation is successful. */ public boolean deQueue() { if(isEmpty()){ return false; } queue[head] = null; head = (head + 1) % queue.length; return true; } /** Get the front item from the queue. */ public int Front() { if(isEmpty()){ return -1; } return queue[head]; } /** Get the last item from the queue. */ public int Rear() { if(isEmpty()){ return -1; } if(tail!=0)return queue[tail-1]; else return queue[queue.length-1]; } /** Checks whether the circular queue is empty or not. */ public boolean isEmpty() { if(tail == head && queue[tail] == null){ return true; } return false; } /** Checks whether the circular queue is full or not. */ public boolean isFull() { if(head == tail && queue[tail] != null){ return true; } 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(); */