2016-03-06 120 views
-1

我一直在教自己的Java与http://www.cs.princeton.edu/courses/archive/spr15/cos126/lectures.html作为参考。我正要过的Stack的话题,他们有以下代码为例索引混淆堆栈LIFO

import edu.princeton.cs.algs4.StdIn; 
import edu.princeton.cs.algs4.StdOut; 

public class StrawStack 
{ 
    private String[] a; 
    private int N=0; 

    public StrawStack(int max) 
    { a = new String[max];} 

    public boolean isEmpty() 
    { return (N==0);} 

    //push a string on top of the stack 
    public void push(String item) 
    { a[N++] = item;} 

    //return the last string added to the top of the stack 
    // this is what gets printed out in the main method 
    public String pop() 
    { return a[--N]; } 

    public int size() 
    { return N;} 

    public static void main(String[] args) 
    { 
    int max = Integer.parseInt(args[0]); 
    StrawStack stack = new StrawStack(max); 
    while (!StdIn.isEmpty()) 
    { 
     String item = StdIn.readString(); 
     if (item.equals("-")) 
     { StdOut.print(stack.pop() + " ");} 
     else 
     { stack.push(item);} 
    } 
    } 
    //StdOut.println(); 
} 

使用to be or not to – be - - that - - - is作为输入,然后输出to be not that or be,这是有道理的,因为-使代码打印出来的最后串。我的困惑是如何在pop方法中有a[--N]这个结果。我在纸上写出了to be or not to –部分输入内容,并跟踪指数。我以为它会像这样:

(a[0] stays defaulta[1] = toa[2]= bea[3]= ora[4]=nota[5]=to直到它运行到-,那么它在pop调用。我的困惑是,不知何故代码调用弹出并返回a[5] = to而不是a[4] = not,我认为应该是这样。因为右之前它运行到-N = 5然后击打-后,N被分配4如果即时没有错误(我必须)

+0

如果我没有错的,问题是不是关于++ ++和一个,但关于指数是如何使用的堆栈... –

回答

1

在该代码中,N是下一个空的空间的索引,而不是索引最后插入的字符串在堆栈中。所以当做一个[ - N]时,它确实首先减少N,但是它指向最后插入的项目“to”。

遇到当第一“ - ”,堆栈如下:

a[0] = "to" 
a[1] = "be" 
a[2] = "or" 
a[3] = "not" 
a[4] = "to" 

和n是5

+0

谢谢!这非常有意义。出于某种原因,我认为--N和N一样 - – stratofortress