Stack is an ordered collection of items where the addition and removal of items take place at the same end, which is also known as the TOP. The order end of the stack is known as the BASE. The base of the stack is significant because the items that are closer to the base represent those that have been in the stack for the longest time.
The most recently added item is the one that is in the top position so that it can be removed first. The items are added on to the stack using push operation and removed using pop operation.
To understand push and pop, let’s take a look at a familiar situation. Suppose, you start working on a word document, you type in a title and then you change its Font size followed by change of color.
So, you can do whateveryou want to do on the word file but when you hit the undo button, only the last task done is undone.
Similarly, in case of stack you can add as many items you want using push but you can pop or remove only the object which is on the top which means last in is first to be removed. This principle of ordering is known as LIFO that stands for Last-in-first-out, where the newer items are near the top, while older items are near the base.
Stacks are important because they are required whenever there is a need to reverse the order of items as the order of removal is reverse of the order of insertion.
Example:
- Pushing back button on browser while surfing on internet.
- Ctrl+Z(undo) in Microsoft applications
- Remove recently used object from cache.
Stacks are commonly used by software programmers, it may not be quite noticeable while using a program as these operations generally take place at the background. However, many times you may come accross Stack overflow error. This happens when a stack actually runs out of memory.
Stacks seem to be very simple. Yet they are one of the most important data structures as you will see very soon. Stacks serve as a very important element of several data structures and algorithms.