I’m thinking the same thing… if indexOfTop points at the top-most element, then setting that same index to the new value just keeps overwriting that top-most element, no?
Edit: I actually tried it the way I thought it should be (adding 1 to the value of indexOfTop) and it definitely does not do the right thing (the first element of every stack is empty, so everything is off by 1). And when I removed that code, it worked perfectly.
So, now my only question is: How is it working!? How can indexOfTop be used to both show the top-most element and to insert a new element?
It works because of the line immediately preceding that line:
this.sizes[stackNumber]++;
That seems tricky – difficult to come back to later on and immediately understand how those lines work in concert. Perhaps it would be more straight-forward to swap those two lines and add 1 to the indexOfTop instead:
// insert our new value to the top of the stackthis.values[this.indexOfTop(stackNumber)+1]=value;// increment our stack size by 1this.sizes[stackNumber]++;
I’m thinking the same thing… if
indexOfTop
points at the top-most element, then setting that same index to the newvalue
just keeps overwriting that top-most element, no?Edit: I actually tried it the way I thought it should be (adding 1 to the value of
indexOfTop
) and it definitely does not do the right thing (the first element of every stack is empty, so everything is off by 1). And when I removed that code, it worked perfectly.So, now my only question is: How is it working!? How can
indexOfTop
be used to both show the top-most element and to insert a new element?Oh. I see it now 🤦🏻♂️!
It works because of the line immediately preceding that line:
That seems tricky – difficult to come back to later on and immediately understand how those lines work in concert. Perhaps it would be more straight-forward to swap those two lines and add 1 to the
indexOfTop
instead:It is a bit convoluted eh?
Yeah, maybe a little. Not too bad. Once I actually ran the code, I began to understand the cleverness at work.