0
大家好,非常感謝對我的支持。ArrayBased Stack實現pop()s [top] = null,top--和s [ - top] = null之間是否有區別?
我的問題真的很短,而且具體。
直接附加操作pop(),與ArrayStack實現有關。
public E pop() throws EmptyStackException {
if (isEmpty()){
throw new EmptyStackException();
}
E temp = s[top];
s[--top] = null;
return temp;
}
據堆棧,彈出操作減少頂在了這句話的基於陣列的實現:
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;
}
}
有一個區別,因爲這是相反的方式,但是,你可以將它分開。 – harold
你是什麼意思?你能分步解釋java如何看這句話嗎[ - top] = null; – Uhel
'--top'減少'top'並評估爲新值。 'top - '遞減'top',但是評估爲* old *的值。 – harold