A stack is a linear data structure that follows the LIFO (Last In, First Out) principle. The last element inserted is the first one to be removed. Stacks are used in many real-world applications like undo systems, backtracking, expression parsing, and function calls.
Concept of a Stack (LIFO)
- Push: add an element to the top
- Pop: remove the top element
- Peek/Top: view the top element without removing
- isEmpty: check if stack is empty
Implementation of Stack Using List
Python lists naturally support stack operations because append() adds to the end and pop() removes from the end.
Example:
stack = []
stack.append(10) # push
stack.append(20)
stack.append(30)
print(stack) # [10, 20, 30]
stack.pop() # pop
print(stack) # [10, 20]
Common Stack Operations
Push
stack.append(5)
Pop
top = stack.pop()
Peek
top = stack[-1]
isEmpty
is_empty = len(stack) == 0
Applications of Stacks
Expression Evaluation (Balanced Parentheses)
Example:
def is_balanced(s):
stack = []
for ch in s:
if ch == '(':
stack.append(ch)
elif ch == ')':
if not stack:
return False
stack.pop()
return len(stack) == 0
print(is_balanced("(())")) # True
print(is_balanced("(()")) # False
Undo Mechanism
- Push actions to stack
- Pop to undo last action
Backtracking
Used in problems like:
- Maze solving
- N-Queens
- DFS traversal
Summary
Stacks are simple but powerful. Once you master them, many problems (parentheses, next greater element, backtracking) become much easier.
Leave a Reply