Stack
In this lecture, you will learn about the stack data structure and its implementation in Python
A stack is a linear data structure that follows the principle of Last In First Out (LIFO). 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
Look at 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.
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.
We can implement a stack in any programming language like C, C++, Java, Python or C#, but the specification is pretty much the same.
Basic Operations of Stack
There are some basic operations that allow us to perform different actions on a stack.
Push: Add an element to the top of a stack
Pop: Remove an element from the top of a stack
IsEmpty: Check if the stack is empty
IsFull: Check if the stack is full
Peek: Get the value of the top element without removing it
Working of Stack Data Structure
The operations work as follows:
A pointer called TOP is used to keep track of the top element in the stack.
When initializing the stack, we set its value to -1 so that we can check if the stack is empty by comparing
TOP == -1
.On pushing an element, we increase the value of TOP and place the new element in the position pointed to by TOP.
On popping an element, we return the element pointed to by TOP and reduce its value.
Before pushing, we check if the stack is already full
Before popping, we check if the stack is already empty
Implementation of Stack Data Structure
We can implement a stack in Python using a list. The list will act as the stack itself and the append()
and pop()
methods will be used to add and remove elements from the stack.
Output
Applications of Stack Data Structure
Stacks are used in many applications. Some of them are:
Balancing of symbols: In compilers, the parentheses, braces, and brackets are checked for their matching. This can be easily done using a stack.
Infix to Postfix Conversion: In compilers, the infix expression is converted to postfix expression. This too can be done using a stack.
Undo mechanism in editors: The undo mechanism in editors like Microsoft Word can be easily implemented using a stack.
Forward and backward feature in web browsers: The forward and backward feature in web browsers store the history of visited pages. This too can be implemented using a stack.
Used in many algorithms like Tower of Hanoi, tree traversals, stock span problem, histogram problem.
Last updated