我一直在教自己的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 default
a[1] = to
a[2]= be
a[3]= or
a[4]=not
a[5]=to
直到它运行到-
,那么它在pop
调用。我的困惑是,不知何故代码调用弹出并返回a[5] = to
而不是a[4] = not
,我认为应该是这样。因为右之前它运行到-
,N = 5
然后击打-
后,N
被分配4
如果即时没有错误(我必须)
如果我没有错的,问题是不是关于++ ++和一个,但关于指数是如何使用的堆栈... –