Stack is one of the most popular and widely known data structures in computer science, and one of the easiest to learn and understand. But often, maybe because of the way it is introduced or taught, it seems kind of useless and boring to learn.
A stack is a linear Last-In-Last-Out (LIFO) data structure which means that the last element added to the stack will be the first one to be removed. Therefore, once a new element is added to the stack, all elements that were added after it has to be removed before the new element can be removed.
Basic features of Stack
1. Stack is an ordered list of similar data type.
2. Stack is a LIFO(Last in First out) structure or we can say FILO(First in Last out).
3. push() function is used to insert new elements into the Stack and pop() function is used to remove an element from the stack. Both insertion and removal are allowed at only one end of Stack called Top.
4. Stack is said to be in Overflow state when it is completely full and is said to be in Underflow state if it is completely empty.
Algorithm for PUSH operation
Check if the stack is full or not.
If the stack is full, then print error of overflow and exit the program.
If the stack is not full, then increment the top and add the element.
Algorithm for POP operation
Check if the stack is empty or not.
If the stack is empty, then print error of underflow and exit the program.
If the stack is not empty, then print the element at the top and decrement the top.
Implementation in Python
Implementation in C++
Applications of Stack Data Structure
Although stack is a simple data structure to implement, it is very powerful. The most common uses of a stack are:
1. To reverse a word - Put all the letters in a stack and pop them out. Because of the LIFO order of stack, you will get the letters in reverse order.
2. In compilers - Compilers use the stack to calculate the value of expressions like 2 + 4 / 5 * (7 - 9) by converting the expression to prefix or postfix form.
3. In browsers - The back button in a browser saves all the URLs you have visited previously in a stack. Each time you visit a new page, it is added on top of the stack.
When you press the back button, the current URL is removed from the stack, and the previous URL is accessed.
For the array-based implementation of a stack, the push and pop operations take constant time, i.e. O(1).
With this article at Logicmojo, you must have the complete idea of analyzing Stack Data Structure.
Good Luck & Happy Learning!!