大家好,非常感谢给予我任何支持。
我的问题非常简短,具体。
直接我附加与ArrayStack Implementation相关的操作pop()。
public E pop() throws EmptyStackException {
if (isEmpty()){
throw new EmptyStackException();
}
E temp = s[top];
s[--top] = null;
return temp;
}
根据基于Array的Stack实现,pop语句在这句话中减少了顶部:
s[--top] = null;
然而,我发现这非常令人困惑,为什么不是这样:
s[top] = null;
top--;
我理解这两项操作都做同样的工作。但是我无法弄清楚它是如何用s[top--] = null
完成的。是否设置s[top] = null
,然后按top--;
。这是一步完成的吗?
感谢。
完整的参考类别:
public class ArrayBasedStack {
protected E s[];
protected int top = -1;
public ArrayBasedStack(int cap){
s = (E[]) new Object[cap];
}
public int size(){
return top + 1;
}
public boolean isEmpty(){
if(top < 0){
return true;
}
return false;
}
public E top() throws EmptyStackException {
if (isEmpty()) {
throw new EmptyStackException("Stack is empty.");
}
return S[top];
}
public E pop() throws EmptyStackException {
if (isEmpty()){
throw new EmptyStackException();
}
E temp = s[top];
s[--top] = null;
return temp;
}
public void push(E element) throws FullStackException {
if (size() == capacity){
throw new FullStackException("Stack is full.");
}
S[++top] = element;
}
}
答案 0 :(得分:0)
s[--top] = null;
首先递减索引 ,然后索引数组。
s[top] = null;
top--;
索引数组,然后 second 递减索引。它也可能存在ArrayIndexOutOfBoundsException
的风险。