Data Structures: Stack - Notes & Programs
6.1 Stack
A stack is a linear data structure that follows the LIFO (Last In, First Out) principle.
The element inserted last is the first one to be removed.
Example in real life: A pile of plates – the last plate kept is the first one removed.
Python Example:
stack = [] # empty stack
6.2 Operations on a Stack
6.2.1 Push Operation
Adds an element on the top of the stack.
stack = []
[Link](10) # Push 10
[Link](20) # Push 20
print(stack) # [10, 20]
6.2.2 Pop Operation
Removes the topmost element of the stack.
stack = [10, 20, 30]
print([Link]()) # 30 removed
print(stack) # [10, 20]
6.2.3 Some Important Terms Related to Stacks
- Top: The position of the last inserted element (the topmost element).
- Overflow: When trying to push an element into a full stack.
- Underflow: When trying to pop an element from an empty stack.
Python Example:
stack = []
# Checking Underflow (pop on empty stack)
if len(stack) == 0:
print("Stack Underflow! Cannot pop from empty stack")
# Pushing elements
[Link](1)
[Link](2)
[Link](3)
print("Stack:", stack)
print("Top element is:", stack[-1]) # Top element
# Popping elements
while len(stack) > 0:
print("Popped:", [Link]())
# Now stack is empty
if len(stack) == 0:
print("Stack Underflow again!")
6.3 Implementation of Stacks using a List
6.3.1 Creating a Stack
stack = []
print("Stack created:", stack)
6.3.2 Adding Elements to a Stack
stack = []
[Link]("A")
[Link]("B")
[Link]("C")
print("Stack after adding elements:", stack)
6.3.3 Deleting Elements from a Stack
stack = ["A", "B", "C"]
print("Initial Stack:", stack)
[Link]()
print("After Deleting one element:", stack)
[Link]()
print("After Deleting another element:", stack)