使用循环数组实现队列

use*_*434 2 java algorithm queue implementation data-structures

我正在阅读DynaArrayQueue的实现(当没有足够的元素时,队列的大小加倍)

我对其中的两种方法有一些疑问.

容量是队列的容量.

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;
 }
Run Code Online (Sandbox Code Playgroud)

在计算尺寸时我们使用的原因

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;

}


  }
Run Code Online (Sandbox Code Playgroud)

方法中的第一个for循环是直接的,但为什么我们需要第二个if循环呢?.这是什么条件照顾?

Her*_*ton 8

容量的原因是因为

(rear - front) 
Run Code Online (Sandbox Code Playgroud)

可以是负的,负模数因语言实现而异.

你有第二个循环的原因是因为

在这种情况下

[#####000000####]
     ^      ^
    rear   front

# is array item
0 is empty space
Run Code Online (Sandbox Code Playgroud)

复制到更大的数组时,会得到一个脱节的数组

[#####000000####000000000000000]
Run Code Online (Sandbox Code Playgroud)

第二个循环移动

[#####000000####000000000000000]
 ^---^
Run Code Online (Sandbox Code Playgroud)

[00000000000#########0000000000]
                ^---^
Run Code Online (Sandbox Code Playgroud)