LeetCode 上 关于问题:622. 设计循环队列,老师,我参照之前咱们写的LoopQueue代码,写了一套,但是在获取队列尾部元素的时候有点问题,tail和tail+1有点被绕晕了,回去查看了一下PDF文档,还是不明白这地方,希望老师能帮我解释一下,tail这个位置,到底存放不存放元素,tail+1的位置存不存放元素,现在对这两个位置的概念,有点模糊,我先贴一下我的代码:
public class MyCircularQueue {
private int[] array;//利用数据来实现
private int front, tail;//头部和尾部的数组向量坐标
private int size;
/**
* Initialize your data structure here. Set the size of the queue to be k.
*/
public MyCircularQueue(int capacity) {
this.array = new int[capacity + 1];//要空出一个元素来,不参与size计数,只是为了front和tail后续位置的不重叠,实际容量为capacity
this.front = this.tail = 0;
this.size = 0;
}
/**
* Insert an element into the circular queue. Return true if the operation is successful.
*/
public boolean enQueue(int value) {
if (!this.isFull()) {
this.array[tail] = value;
this.tail = (tail + 1) % array.length;
this.size++;
return true;
}
return false;
}
/**
* Delete an element from the circular queue. Return true if the operation is successful.
*/
public boolean deQueue() {
//把front往前挪一个位置
if (!this.isEmpty()) {
front = (front + 1) % array.length;
this.size--;
return true;
}
return false;
}
/**
* Get the front item from the queue.
*/
public int Front() {
return this.array[front];
}
/**
* Get the last item from the queue.
*/
public int Rear() {// 1 2 3 4
return this.array[tail % array.length];
}
/**
* Checks whether the circular queue is empty or not.
*/
public boolean isEmpty() {
return this.front == this.tail;
}
public String toString() {
//此处的理解,需要加深
StringBuilder loopQueue = new StringBuilder();
loopQueue.append(String.format("LoopQuene:size=%d\n", size));
loopQueue.append("front[");
for (int i = front; i != tail; i = (i + 1) % array.length) {
loopQueue.append(array[i]);
if ((i + 1) % array.length != tail) {
loopQueue.append(",");
}
}
loopQueue.append("]tail");
return loopQueue.toString();
}
/**
* Checks whether the circular queue is full or not.
*/
public boolean isFull() {
return ((this.tail + 1) % array.length) == this.front;
}
public static void main(String[] args) {
MyCircularQueue circularQueue = new MyCircularQueue(3); // 设置长度为3
System.out.println(circularQueue.enQueue(1));
; // 返回true
System.out.println(circularQueue.enQueue(2));
; // 返回true
System.out.println(circularQueue.enQueue(3));
; // 返回true
System.out.println(circularQueue.toString());
System.out.println(circularQueue.enQueue(4));
; // 返回false,队列已满
System.out.println(circularQueue.Rear());
; // 返回3
System.out.println(circularQueue.isFull());
; // 返回true
System.out.println(circularQueue.deQueue());
; // 返回true
System.out.println(circularQueue.toString());
System.out.println(circularQueue.enQueue(4));
; // 返回true
System.out.println(circularQueue.toString());
System.out.println(circularQueue.Rear());
; // 返回4
}