我正在阅读dynarrayqueue的实现(当没有足够的元素时,队列的大小会加倍)
我对其中的两种方法有一些疑问。
设capacity为队列的容量。
getQueueSize()方法

public int getQueueSize()
 {
if(front == -1) return 0;

//Here why can't the size by  simply [(rear -front +1) %capacity ]
int size = (capacity - front + rear +1) % capacity;

if(size == 0) return capacity;
else return size;
 }

在计算尺寸时,为什么要使用
大小=(容量-前+后+1)%容量,而不是简单的(后-前+1)%容量。是吗?
问题2:
resizeQueue()
这是调整队列大小的方法
  private void resizeQueue()
 {
int initCapacity = capacity;
capacity *=2;

int[] oldArray = array;

array = new init[this.capacity];

//this is fine
for(int i=0; i<oldArray.length;i++)
{
    array[i] =oldArray[i];
}

//why do we need this ?
if(rear < front)
{
    for(int i =0 ; i<front ; i++)
    {
        array[i+initCapacity] = this.array[i];
        array[i]= null;

    }

    rear = rear + initCapacity;

}


  }

方法中的第一个for循环是直接向前的,但是为什么我们需要第二个if循环?。它在处理哪些条件?

最佳答案

一之所以有能力是因为

(rear - front)

可以是负模,负模随语言实现而变化。
2.你有第二个循环的原因是
在这种情况下
[#####000000####]
     ^      ^
    rear   front

# is array item
0 is empty space

当你复制到一个更大的数组时,你会得到一个不相连的数组
[#####000000####000000000000000]

第二个循环移动
[#####000000####000000000000000]
 ^---^


[00000000000#########0000000000]
                ^---^

10-01 14:59
查看更多