Pushing an element into the stack
A stack is a linear data structure that follows the principle of Last In First Out (LIFO). It is a collection of items of the same type. This means the last element inserted inside the stack is removed first.
You can think of the stack data structure as the pile of plates on top of another. Here, you can:
- Put a new plate on top
- Remove the top plate
And, if you want the plate at the bottom, you must first remove all the plates on top. This is exactly how the stack data structure works.
Algorithm
LIFO Principle of Stack
In programming terms, putting an item on top of the stack is called push and removing an item is called pop.
In the above image, although item 3 was kept last, it was removed first. This is exactly how the LIFO (Last In First Out) Principle works.
Here, we are going to focus on the push operation for now.
Push: Adds an item to the stack. If the stack is full, then it is said to be an Overflow condition.