I'm trying to implement a reverse stack where items are inserted at the bottom and popped at the bottom of the stack. I know how to implement a regular stack however when I tried to modify the code to do it in a reverse order I keep getting an error.
Any assistance is appreciated.
Thanks in advance
What you're building is called a queue or a FIFO queue. FIFO stands for First In First Out.
Suppose you insert numbers 1,5,7. The queue looks like this:
1 5 7
Now remove 1:
5 7
Now if you remove 5, where will you remove it from? What is the index? Or what is the pointer?
My point here is that both your top and bottom pointers must move. One moves when you insert, and one moves you remove.
If you do this with a fixed sized buffer then you want to treat it like a circular buffer. You keep one pointer (or index) that points to the where you'll insert, and a separate pointer (or index) that points where you'll remove the next item.
When either pointer reaches the end of the buffer, it wraps back around to the beginning.
The buffer is full when when the insert pointer overtakes the remove pointer. It's empty when the remove pointer overtakes the insert pointer.
To code this without going completely crazy, you MUST define ahead of time exactly what the pointers mean. Do you insert at the and then increment, or increment and then insert? Ditto for deleting. Pick a strategy first. Put it in your comments and then stick to it.