2017-05-09 64 views
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; 
} 

}

+0

有一个区别,因为这是相反的方式,但是,你可以将它分开。 – harold

+0

你是什么意思?你能分步解释java如何看这句话吗[ - top] = null; – Uhel

+0

'--top'减少'top'并评估为新值。 'top - '递减'top',但是评估为* old *的值。 – harold

回答

0
s[--top] = null; 

递减索引第一,然后索引阵列。

s[top] = null; 
top--; 

索引阵列,然后递减索引。它也可能冒ArrayIndexOutOfBoundsException风险。

相关问题