Stack





Definition: A collection of elements that are stored on top of one another so that insertion and deletion only takes place at the top of the structure. This can be referred to simply by the phrase "last in, first out".



Real Life Example: Imagine that you have a pile of heavy textbooks stacked on top of one another. If you would like to add a new book to the pile, you can add it by placing it on top of the pile. Similarily, if you would like to remove a certain book, you must start from the top of the pile and remove all books on top of that particular book before reaching and removing it. In summary, all operations begin at the top of the stack.


Note: The top-most element in a stack is always referred to as the "top".



Basic Stack Operations:

  1. Pushing an element. An element is added to the stack by being placed on top of it.
  2. Popping an element. The top element is removed from the stack.


Fun Fact: Have you every made a mistake when typing an essay in Microsoft Word or Google Docs and hit the undo button? This is managed by a stack! Everytime you make a change to the essay, that version is pushed onto a stack and whenever you hit undo, the current version is popped and the previous version is restored.



Commonly Used In: