class ArrayBasedDeque<EltType> {
private final int CAPACITY = 10;
private int capacity;
private int end;
private EltType deque[];
public ArrayBasedDeque() {
this.capacity = CAPACITY;
deque = (EltType[]) (new Object[capacity]);
}
public EltType removeFirst() {
EltType[] tempArray;
EltType returned = deque[0];
tempArray = (EltType[]) new Object[capacity];
for (int i=1;i<capacity;i++) {
tempArray[i-1] = deque[i];
}
deque = tempArray;
return returned;
}
public boolean isEmpty() {
return end == 0;
}
public void insertFirst(EltType first) {
if(!isEmpty()) {
EltType[] tempArray;
tempArray = (EltType[]) new Object[capacity+1];
for (int i=0;i<deque.length;i++) {
tempArray[i+1] = deque[i];
}
deque = tempArray;
}
deque[0] = first;
}
}
谢谢:)
答案 0 :(得分:3)
明显的问题是end
永远不会改变。 isEmpty()
将始终返回true
。现在让我们看看你的insertFirst()
方法。
public void insertFirst(EltType first) {
if(!isEmpty()) {
EltType[] tempArray;
tempArray = (EltType[]) new Object[capacity+1];
for (int i=0;i<deque.length;i++) {
tempArray[i+1] = deque[i];
}
deque = tempArray;
}
deque[0] = first;
}
知道isEmpty()
总是返回true
无论如何,这段代码有什么问题?
答案 1 :(得分:2)
删除元素时,您还需要更新结束指针。
您还应该调查System.arrayCopy()