递减字段大小和 dequeue() 方法

问题描述 投票:0回答:0

我正在尝试使用类似数组的队列(循环队列)并尝试使第一个元素出队。这是我的实现,但是,它没有在删除最后一个对象的地方正确地减少 size 变量。为什么会这样?

public Bottle dequeue() throws NoSuchElementException {
    if (isEmpty() || front == -1) {
        throw new NoSuchElementException("queue is empty");
}
Bottle tempt = bottles\[front\];
if (front == back) { // when there is only one element in the queue
    front = -1;
    back = -1;
    return tempt;
}
if (front == size - 1) { // when front is the end of the array, set it to first index
    front = 0;
} else if (back == 0) {
    front = back;
} else { // when front is not the end of the array nor
    front = (front) % bottles.length;
}
bottles\[front\] = null;
return tempt;
}

当我尝试添加“size--;”在所有 if 和 else 语句之后,它删除了我的最后一个元素。

java queue computer-science
© www.soinside.com 2019 - 2024. All rights reserved.