2017-05-09 22 views
0

こんにちはみなさん、私に与えられたサポートに感謝します。ArrayBasedのスタック実装pop()s [top] = null、top-とs [ - top] = nullの間に違いはありますか?

私の質問は、実際には短く、具体的です。

Straight away ArrayStackの実装に関連して、操作pop()をアタッチします。

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--;に従ってください。これは1つのステップで行われますか?

ありがとうございました。参考のために

完全なクラス:

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

これは逆のために違いがありますが、それを分けることができます。 – harold

+0

他の方法ではどういう意味ですか? javaがこの文をどのように見えるかを段階的に説明できますか?[ - top] = null; – Uhel

+0

'--top'は' top'を減らし、新しい値を評価します。 'top - 'は 'top'を減らしますが、* old *値を評価します。 – harold

答えて

0
s[--top] = null; 

は、インデックス最初、索引アレイをデクリメントします。

s[top] = null; 
top--; 

索引アレイは、インデックスをデクリメントします。また、ArrayIndexOutOfBoundsExceptionのリスクもあります。