【发布时间】:2022-01-19 15:47:43
【问题描述】:
我正在阅读我在 Github 中偶然发现的队列实现,并且很难理解为什么使用某些行为。 (可以找到存储库的链接here)
- 该代码将用户期望声明队列大小的初始容量加 1。店主解释说这是因为初始最大大小是data.length - 1,但没有解释原因。这是该部分的代码:
public ArrayQueue(int capacity) {
// ArrayQueue maximum size is data.length - 1.
data = new Object[capacity + 1];
front = 0;
rear = 0;
}
- 我不确定为什么在 offer 函数中已经将项目插入队列后调整后索引,但在轮询中先调整头部索引。有什么不同吗?
public void offer(T elem) {
if (isFull()) {
throw new RuntimeException("Queue is full");
}
data[rear++] = elem;
rear = adjustIndex(rear, data.length);
}
public T poll() {
if (isEmpty()) {
throw new RuntimeException("Queue is empty");
}
front = adjustIndex(front, data.length);
return (T) data[front++];
}
- 为什么我们需要在(前-后)添加 data.length 来检查列表是否已满?
public boolean isFull() {
return (front + data.length - rear) % data.length == 1;
}
谢谢
【问题讨论】: