【发布时间】:2013-09-23 03:59:38
【问题描述】:
我正在尝试使用数组实现队列。 (不使用内置的 Java Queue 函数)。但是,在测试时,数组只会在 size ==maxSize 时打印出来(因为数组的大小达到了 maxSize/容量)。除了在大小小于 maxSize 时不打印之外,测试用例通过。 (它是一个双端队列,因此可以在前后添加元素)。有什么建议吗?
package vipQueueArray;
import java.util.NoSuchElementException;
public class vipQueue {
private Object[] array;
private int size = 0;
private int head = 0; // index of the current front item, if one exists
private int tail = 0; // index of next item to be added
private int maxSize;
public vipQueue(int capacity) {
array = new Object[capacity];
maxSize = capacity;
size = 0;
tail = maxSize - 1;
}
public Object Dequeue() {
if (size == 0) {
throw new NoSuchElementException("Cant remove: Empty");
}
Object item = array[head];
array[head] = null;
head = (head + 1) % array.length;
size--;
return item;
}
public void EnqueueVip(Object x) {
if (size == maxSize) {
throw new IllegalStateException("Cant add: Full");
}
array[tail] = x;
tail = (tail - 1) % array.length;
size++;
}
public void Enqueue(Object y) {
if (size == maxSize) {
throw new IllegalStateException("Cant add: Full");
}
array[head] = y;
head = (head + 1) % array.length;
size++;
}
public boolean isFull() {
return (size == maxSize);
}
public boolean isEmpty() {
return (size == 0);
}
}
public class Test{
public static void main(String[] args){
vipQueue Q = new vipQueue(2);
Q.Enqueue(4);
System.out.printf("->%d", Q.Dequeue());
} }
【问题讨论】:
-
我在代码中找不到任何问题,除了如何将元素添加到队列的前面。我认为问题出在测试用例本身,您也可以发布它吗?
-
posted,所以maxSize为2,只添加了一个元素。但出队打印出 null
-
Enqueue和Dequeue都使用head。我希望它来自堆栈,而不是队列。 -
@MarkPeters 对于这个实现它实际上很好,你不能“告诉”作为用户,如果你应该从头部或尾部出队,他的
dequeue实现会照顾以一种非常优雅的方式(模数)。 -
@alfasin:如果您期望 FIFO 行为,那就不好了,这就是队列。我并不是说添加到尾部还是头部都重要,但是为两者使用一个光标变量似乎没有意义。