【发布时间】:2018-07-12 11:55:25
【问题描述】:
我正在尝试完全实现 Deque,而不使用 java 库中已经创建的 Deque。我的代码可以编译,但输出并不像预期的那样。例如,容量应该作为参数提供给类,但结果显示实际容量最终比指定的量低 1。
我遇到的另一个问题是队列应该按照先进先出的方式工作。但这在结果中没有体现。有什么想法吗?
public class ArrayDeque<E> implements IDeque<E> {
private int capacity;
private E[] array;
private int front;
private int end;
private int size;
public ArrayDeque(int capacity) {
this.array = (E[]) new Object[capacity];
this.capacity = capacity - 1;
front = 1;
end = 0;
size = 0;
}
private boolean isFull() {
return (size == capacity);
}
private boolean isEmpty() {
return (size == 0);
}
@Override
public int size() {
return size;
}
@Override
public void addFirst(E elem) throws DequeFullException {
if (isFull())
throw new DequeFullException("samlingen er full!");
array[front] = elem;
front = (front + 1) % capacity; // use modulo to make sure the front restarts from initial position once it reaches capacity
size++;
}
@Override
public E pullFirst() throws DequeEmptyException {
if (isEmpty())
throw new DequeEmptyException("Samlingen er tom!");
front = (front - 1) % capacity;
size--;
return array[front];
}
@Override
public E peekFirst() throws DequeEmptyException {
if (isEmpty())
throw new DequeEmptyException("samlingen er tom!");
System.out.println(array[(front - 1) % capacity]);
return array[(front - 1) % capacity];
}
@Override
public void addLast(E elem) throws DequeFullException {
if (isFull())
throw new DequeFullException("samlingen er full!");
array[end] = elem;
end = (end - 1) % capacity;
size++;
}
@Override
public E pullLast() throws DequeEmptyException {
if (isEmpty())
throw new DequeEmptyException("samlingen er tom!");
end = (end + 1) % capacity;
size--;
return array[end];
}
@Override
public E peekLast() throws DequeEmptyException {
if (isEmpty())
throw new DequeEmptyException("samlingen er tom!");
System.out.println(array[(end + 1) % capacity]);
return array[(end + 1) % capacity];
}
}
public class Main {
public static void main(String[] args){
ArrayDeque<String> deque = new ArrayDeque<>(6);
deque.addFirst("first");
deque.addFirst("second");
deque.addFirst("third");
deque.addFirst("fourth");
deque.peekFirst();
deque.peekLast();
deque.addLast("fourth");
deque.addLast("last");
deque.peekLast();
deque.size();
}
}
【问题讨论】:
-
为什么你的双端队列从索引 1 开始?
-
"但结果显示实际容量最终比指定的数量低 1" - 可能是
this.capacity = capacity - 1;的原因?