抱歉,下面是我在这里遇到的一个问题:在这里,我试图运行此方法以从双面队列(双端队列)中删除通用值(EltType),但是我一直遇到错误,我两次调用insertFirst ,然后将值“ 3”插入数组两次,然后,当我运行removeFirst时,它将打印出“ 3”一次,然后打印出“ Null”。有人可以帮我吗?
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; } }
谢谢 :)
明显的问题是它end永远不会改变。 isEmpty()将永远返回true。现在,让我们看看您的insertFirst()方法。
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,这段代码有什么问题?