我收到一个错误:
java.lang.ArrayIndexOutOfBoundsException: -1
它指的是方法注入:
deque[back] = x;
我也有 push 和 pop 的方法,可以在前面添加和删除项目,但工作正常。
这个想法是使用基于数组的实现作为双端队列,其中在后面注入和弹出插入项目并在后面删除项目。
public void inject(int x){
if (elementCount == size){
System.out.println("The Deque is Full");
} else {
deque[back] = x;
back = (back - 1) % size;
elementCount ++;
}
}
public class Deque {
int[] deque;
int front;
int back;
int size;
int elementCount;
public Deque(int s){
size = s;
deque = new int[size];
front = 1;
back = 0;
elementCount = 0; //n of elements
}
public int getRear(){
return deque[back];
}
public int getFront(){
return deque[front];
}
public void inject(int x){
if (elementCount == size){
System.out.println("The Deque is Full");
} else {
deque[back] = x;
back = (back - 1) % size;
elementCount ++;
}
}
public void eject(){
if (elementCount == 0){
System.out.println("The deque is empty");
}else{
back = (back + 1) % size;
elementCount--;
}
}
}