[英]Circular Queue Implementation in Java
I was reading a queue implementation that I stumbled upon in Github and was having difficulty understanding why certain behaviors were used.我正在阅读我在 Github 中偶然发现的队列实现,并且很难理解为什么使用某些行为。 (The link to the repository could be found here )
(可以在此处找到存储库的链接)
public ArrayQueue(int capacity) {
// ArrayQueue maximum size is data.length - 1.
data = new Object[capacity + 1];
front = 0;
rear = 0;
}
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++];
}
public boolean isFull() {
return (front + data.length - rear) % data.length == 1;
}
Thank you谢谢
ArrayQueue maximum size is data.length - 1. The place of the variable rear is always in front of the variable front logistically if regard the data array as circular.
ArrayQueue 最大大小为 data.length - 1。如果将数据数组视为循环,则变量的位置在逻辑上总是在变量 front 的前面。 so the number of states of the combination of rear and front is the length of the data array.
所以前后组合的状态数就是数据数组的长度。 And one of the total states is used to be the judge if the queue is empty or full.
并且总状态之一用于判断队列是空的还是满的。
read
is adjusted after because rear
is the place where the new element is supposed to be added. read
是在后面调整的,因为rear
是应该添加新元素的地方。 After the element is added, it is incremented.front
is the index where the element is supposed to be popped out, because it alread has the element.front
是元素应该被弹出的索引,因为它已经有了元素。data.length - 1
so front - rear
has to equal 1
if the queue is supposed to be full.data.length - 1
所以如果队列应该是满的, front - rear
必须等于1
。 I hope this answers your question.我希望这回答了你的问题。 Feel free to ask questions in the comments.
随时在评论中提问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.