多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
``` class MyCircularQueue { private int[] data; private int head; private int tail; private int size; /** Initialize your data structure here. Set the size of the queue to be k. */ public MyCircularQueue(int k) { data = new int[k]; head = -1; tail = -1; //size是队列的容量,数组的大小,为data.length,数组从0到 k-1 , ( k-1)+1 % k ==0,索引从末尾变为index = 0。 //0到k-2坐标设为a, (a+1)%k = a+1 size = k; } public boolean enQueue(int value) { //队列满不能入队 if (isFull() == true) { return false; } //队列空,头指针需要初始化为0 if (isEmpty() == true) { head = 0; } //队尾指针移动到下一个位置,插入的第一个元素位置为(-1+1)%size =0 tail = (tail + 1) % size; data[tail] = value; return true; } public boolean deQueue() { //队为空,出队失败 if (isEmpty() == true) { return false; } //如果head == tail 时,表明队列中还有一个元素,这时队头队尾指针都指向这个元素。 //这时调用出队方法,队为空,head与tail都需要变为-1 if (head == tail) { head = -1; tail = -1; return true; } //head指针向下移动一位,表示队头元素已经出队 head = (head + 1) % size; return true; } public int Front() { if (isEmpty() == true) { return -1; } //返回队头元素 return data[head]; } public int Rear() { //队空时,head==tail== -1 if (isEmpty() == true) { return -1; } //返回队尾元素 return data[tail]; } //队空时,head == -1 public boolean isEmpty() { return head == -1; } // (tail+1)%size +1 == head时,队满, 队尾不能再插入元素 public boolean isFull() { return ((tail + 1) % size) == head; } } ```