Java 创建出列
我正在尝试创建一个基于数组的出列,但无法获得正确的输出顺序。 现在它是有界的,但我可能会使用无界一旦我弄明白了如何正确地工作出队列 这是我的密码:Java 创建出列,java,arrays,queue,deque,Java,Arrays,Queue,Deque,我正在尝试创建一个基于数组的出列,但无法获得正确的输出顺序。 现在它是有界的,但我可能会使用无界一旦我弄明白了如何正确地工作出队列 这是我的密码: public class ArrayBndDequeue<T> implements BoundedDequeueInterface<T> { protected final int DEFCAP = 100; // default capacity protected T[] queue;
public class ArrayBndDequeue<T> implements BoundedDequeueInterface<T>
{
protected final int DEFCAP = 100; // default capacity
protected T[] queue; // array that holds queue elements
protected int numElements = 0; // number of elements n the queue
protected int front = 0; // index of front of queue
protected int rear; // index of rear of queue
public ArrayBndDequeue()
{
queue = (T[]) new Object[DEFCAP];
rear = DEFCAP - 1;
}
public ArrayBndDequeue(int maxSize)
{
queue = (T[]) new Object[maxSize];
rear = maxSize - 1;
}
public void enqueue(T element)
// Throws QueueOverflowException if this queue is full;
// otherwise, adds element to the front of this queue.
{
if (isFull())
throw new DequeueOverflowException("Enqueue attempted on a full queue.");
else
{
front = (front + 1) % queue.length;
queue[front] = element;
numElements = numElements + 1;
}
}
public T dequeue()
// Throws QueueUnderflowException if this queue is empty;
// otherwise, removes rear element from this queue and returns it.
{
if (isEmpty())
throw new DequeueUnderflowException("Dequeue attempted on empty queue.");
else
{
T toReturn = queue[rear];
queue[rear] = null;
rear = (rear + 1) % queue.length;
numElements = numElements - 1;
return toReturn;
}
}
public boolean isEmpty()
// Returns true if this queue is empty; otherwise, returns false
{
return (numElements == 0);
}
public boolean isFull()
// Returns true if this queue is full; otherwise, returns false.
{
return (numElements == queue.length);
}
}
输出结果如下:
2
3
1
有什么帮助吗?如果你还需要我的代码,请告诉我 在排队过程中,您首先将+1添加到前面,然后设置对象,但您需要按相反的顺序执行
另一方面,实现您自己的队列类是一个非常糟糕的主意(当然,除非您是为了学习而这样做的),因为Java已经有了一个高速、可靠且经过良好测试的类。您可以查看Java queue类的源代码,了解如何正确地执行它。您描述的问题源于插入过程中的以下表达式(同样适用于删除): 这包括:
(0+1%3)=1
(1+1%3)=2
(2+1%3)=0
3%3
,即0。因此,该值存储在索引0处
请查看中此算法的定义。他们是这样做的:
public void addFirst(E e) {
if (e == null)
throw new NullPointerException();
elements[head = (head - 1) & (elements.length - 1)] = e;
if (head == tail)
doubleCapacity();
}
我认为你的意思如下(尽管你的总体理性是正确的) 更正
(0+1) % 3 = 1
(1+1) % 3 = 2
(2+1) % 3 = 0
而不是您的示例(因为%运算符具有更高的优先级,相当于从左到右的乘法或除法):
为什么有“后”和“前”?“numElements”告诉你后面的位置。Front总是在index=0,这部分内容来自于我使用的那本书,它作为常规队列工作得很好,但不是作为出列队列
this.front = (this.front + 1) % this.queue.length;
public void addFirst(E e) {
if (e == null)
throw new NullPointerException();
elements[head = (head - 1) & (elements.length - 1)] = e;
if (head == tail)
doubleCapacity();
}
(0+1) % 3 = 1
(1+1) % 3 = 2
(2+1) % 3 = 0
(0 + 1 % 3) = 1 => 1
(1 + 1 % 3) = 2 => 2
(2 + 1 % 3) = 0 => 3