提交 d6cc5b3f 编写于 作者: GreyZeng's avatar GreyZeng

update code

上级 ba653a31
......@@ -7,37 +7,34 @@ package git.snippet.queueandstack;
public class LeetCode_0622_DesignCircularQueue {
class MyCircularQueue {
private final int[] arr;
private final int limit; // 容量,和arr大小保持一致
private int popIndex;
// private final int limit; // 容量,和arr大小保持一致,可以省略
private int popIndex; // 队列头部指针(指向队列第一个有效元素)
private int pushIndex; // 队列尾部的下一个位置(就是待插入元素的位置)
private int rear; // 队列尾部指针
private int size; // 非常重要,用于判断队列是否满/空
private int size; // 非常重要,标识现在的有效元素有几个,用于判断队列是否满/空
public MyCircularQueue(int k) {
limit = k;
arr = new int[limit];
arr = new int[k];
}
public boolean enQueue(int value) {
if (!isFull()) {
arr[pushIndex] = value;
rear = pushIndex;
pushIndex = next(pushIndex);
size++;
return true;
} else {
if (isFull()) {
return false;
}
size++;
arr[pushIndex] = value;
rear = pushIndex;
pushIndex = next(pushIndex);
return true;
}
public boolean deQueue() {
if (!isEmpty()) {
popIndex = next(popIndex);
size--;
return true;
} else {
if (isEmpty()) {
return false;
}
size--;
popIndex = next(popIndex);
return true;
}
public int Front() {
......@@ -53,12 +50,12 @@ public class LeetCode_0622_DesignCircularQueue {
}
public boolean isFull() {
return size == limit;
return size == arr.length;
}
// 最重要的方法:判断下一个位置,模拟环行为
private int next(int pre) {
return pre + 1 < limit ? pre + 1 : 0;
return pre + 1 < arr.length ? (pre + 1) : 0;
}
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册