简体   繁体   English

Java中的循环队列实现

[英]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 ) (可以在此处找到存储库的链接)

  1. The code adds 1 to the initial capacity that the user expects the queue size to be declared with.该代码将用户期望声明队列大小的初始容量加 1。 The owner explains that this is because the initial maximum size is data.length - 1, but does not explain why.店主解释说这是因为初始最大大小是data.length - 1,但没有解释原因。 Here is that section of the code:这是代码的那部分:
public ArrayQueue(int capacity) {
  // ArrayQueue maximum size is data.length - 1.
  data = new Object[capacity + 1];
  front = 0;
  rear = 0;
}
  1. I am not sure why the rear index is adjusted after the item has already been inserted in the queue within the offer function, yet the head index is adjusted prior in poll.我不确定为什么在商品 function 中的商品已插入队列后调整后索引,但在轮询中调整了头部索引。 Does it make a difference?这有什么不同吗?
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++];
}
  1. Why do we need to add data.length to (front - rear) to check if list is full?为什么我们需要将 data.length 添加到(前 - 后)以检查列表是否已满?
  public boolean isFull() {
    return (front + data.length - rear) % data.length == 1;
  }

Thank you谢谢

  1. He has mentioned it above他在上面提到过

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.并且总状态之一用于判断队列是空的还是满的。

  1. 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.添加元素后,它会递增。 And front is the index where the element is supposed to be popped out, because it alread has the element.front是元素应该被弹出的索引,因为它已经有了元素。
  2. Remember the max no of items is 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM