A stack is a data structure in which items are retrieved in the reverse order that they were added. If you add an item, this item will also be the first one to be removed. This is sometimes abbreviated as LIFO – Last In First Out.
This stack implementation will have 3 methods:
- push: Add a new item on top of the stack
- pop: Remove the item on top of the stack
- peek: Get the value of the item on top of the stack
See it in action here;
Another way of implementing the stack is by using a LinkedList. I am going to be using my LinkedList implementation for this.
Although not as trivial as with using an Array, it is pretty straightforward with the LinkedList:
- Push adds the element at the beginning of the list
- Pop returns the first element of the list and removes it at the same time.
See it in Action here;