gpt4 book ai didi

java - 为什么在java中入队时必须使用(rear+1)%capacity?

转载 作者:太空宇宙 更新时间:2023-11-04 10:24:19 26 4
gpt4 key购买 nike

  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中制作入队函数时?

最佳答案

在单端队列中没有这样的概念。我假设您正在处理 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

等等

关于java - 为什么在java中入队时必须使用(rear+1)%capacity?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50726063/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com