Thursday, August 27, 2015

Programming: An Illustration of Stacks

Stax

http://secondratesnacks.com/

Pringles: "Once you pop, you can't stop."

Yeah, but the only way to eat Pringles or Stax is to
eat the topmost "Pringle" or "Stak".
This is how stacks work -
they're Last In - First Out (LIFO).

In stacks, there is also the push and pop operations.

What are stacks used for?

You're probably using a browser now.
Your browser probably has a Back and Forward button.
That button probably uses a stack implementation.
And how is this so?

You may test the following in another browser window.
Don't close this yet! Hahaha!

Imagine your browser back-forward stack as a snack container.
At first it is empty - it's still in the snack factory.
You just opened your browser, there's nothing to go back/forward to.

After getting to number 5, your stack looks like this, with website # 5 on top:
Now doing a "pop" would require clicking on the back button.
Notice what happened to the forward button. It's now "clickable".
After clicking the back button, this is our stack:

Notice that we have another stack!
This is for the.....
you guessed correctly! the forward button.
And as you may notice, our current location is where the
top of the back stack is.

If we try going to a 6th site while we're on site # 4,
what happens? Let's enter on the address bar:
    6. http://www.fizzbook.com/

What just happened?
We just pushed another chip into our back stack.
This is how our stack looks like now:

And we popped everything in our forward stack.
Try it after clicking on back many times.
Go figure it out! :)

The stack implementation is also used in
Undo/Redo buttons.

Can you think of other implementations of stacks?

No comments:

Post a Comment