J'ai enseigné moi-même Java avec http://www.cs.princeton.edu/courses/archive/spr15/cos126/lectures.html comme référence. Je voulais simplement sur le thème de Stack
et ils avaient le code suivant comme un exempleindexing confusion 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();
}
L'utilisation to be or not to – be - - that - - - is
comme entrée et la sortie est to be not that or be
, ce qui est logique car -
fait l'impression de code la dernière chaîne. Ma confusion est comment cela finit par fonctionner quand il a a[--N]
dans la méthode pop
. J'ai écrit la partie to be or not to –
de l'entrée sur papier et gardé la trace des indices. Je pensais que ça va comme ceci:
(a[0] stays default
a[1] = to
a[2]= be
a[3]= or
a[4]=not
a[5]=to
jusqu'à ce qu'il se jette dans -
, il fait appel à pop
. Ma confusion est, en quelque sorte le code appelle pop et renvoie a[5] = to
au lieu de a[4] = not
, ce qui je pense devrait être le cas. Parce que juste avant qu'elle se jette dans -
, N = 5
puis après avoir frappé -
, N
est attribué, 4
si je ne suis pas trompé (que je dois être)
Si je ne me trompe pas, la question ne concerne pas un ++ et ++ a, mais sur la façon dont les indices sont utilisés par la pile ... –