【问题标题】:why we have to use (rear+1)%capacity in enqueue in java?为什么我们必须在 java 的 enqueue 中使用 (rear+1)%capacity?
【发布时间】:2018-06-06 17:17:37
【问题描述】:
  void enqueue( int item)
{
    if (is Full(this))
        return;
    this.rear = (this.rear + 1)%this.capacity;
    this.array[this.rear] = item;
    this.size = this.size + 1;
    System.out.println(item+ " enqueued to queue");
}

问题是——为什么我们必须这样做 this.rear = (this.rear + 1)%this.capacity;在java中制作入队函数时?

【问题讨论】:

  • 它正在递增 rear 但会环绕,因此它保持在数组的范围内。如果this.rear 等于this.capacity-1(数组的结尾),则(this.rear+1)%this.capacity 的计算结果为零(数组的开头)。

标签: java data-structures queue


【解决方案1】:

在单端队列中没有这样的概念。我假设你正在处理Circular Queuethis.rear = (this.rear + 1)%this.capacity; 用于将后部指向rear+1'th 索引。 (尤其是当后方到达(n-1)th 位置时。)

例如array[10]capacity = 10rear is at arr[9]arr[0..x] (where x<=(n-1)) 为空

在这种情况下,队列应该允许插入,因为数组中仍有空白空间。为此应用公式

  1. rear = 9

    this.rear = (this.rear + 1)%this.capacity;

    this.rear = (9 + 1)%10 = 0 即在0'th 索引处插入

  2. when rear = 2 时类似

    this.rear = (2 + 1)%10 = 3

等等

【讨论】:

    【解决方案2】:

    它是为了实现循环队列,即每次后计数器或前计数器到达数组末尾时返回数组的开头。

    当后计数器小于数组的长度时,后 % 长度 = 后。

    当后计数器等于数组的长度时,后百分比长度为 0,后计数器在下一圈继续。

    最后,当rear大于数组的长度时,rear % length会返回小于数组长度的值,等于rear - (array.length *传递的圈数)。

    因此,通过将尾部除以长度,我们得到余数,这是我们要放置在队列末尾的元素的下一个位置。

    【讨论】:

      猜你喜欢
      • 2018-12-08
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      • 2020-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多