Loading notes...
Loading notes...
Class 12 • Chapter 5
Stacks are simple yet powerful LIFO (Last-In, First-Out) structures used extensively for managing sequential data and tracking program history.
A Stack is a linear data structure that follows a specific order in which operations are performed: **Last-In, First-Out (LIFO)**. Think of a physical stack of plates—the last plate you place on the top is the first one you can remove. Similarly, in a computer's memory, the most recently added piece of data is the first to be accessed. While Python lists are versatile, a Stack is a 'Restricted' data structure because you can only add or remove items from one end, commonly called the 'Top'. This restriction makes the Stack an incredibly efficient tool for specific tasks like reversing a string, undoing actions in a text editor, or managing function calls in a computer's memory.
In any data structure, managing error conditions is as important as the data itself. **Underflow** occurs when you try to 'Pop' (remove) an element from an empty stack—a situation that can lead to program crashes if not handled gracefully. **Overflow**, on the other hand, occurs when you try to 'Push' (add) an element into a stack that has a fixed maximum size and is already full. While Python lists can grow dynamically (making overflow rare), professional developers always include checks like 'if isEmpty()' before attempting extraction to ensure the application remains stable and user-friendly.
def push(stack, item):
stack.append(item)
def pop(stack):
if not stack: # Underflow Check
return "Underflow Error"
return stack.pop()
def peek(stack):
if not stack:
return "Stack is Empty"
return stack[-1]
# Usage
my_stack = []
push(my_stack, 10)
push(my_stack, 20)
print(pop(my_stack)) # Output: 20Stacks are everywhere in modern computing. When you browse the web and click the 'Back' button, you are navigating a stack of URLs. When you use the 'Ctrl+Z' (Undo) shortcut in a word processor, the program pops the last action off a history stack and reverses it. Even more fundamentally, the 'Call Stack' we explored in recursion is a system-level implementation of this data structure, used by the computer to keep track of functioning parts that have not yet finished running. By understanding the Stack, you gain insight into how computers manage state and sequential memory.
def reverse_string(s):
stack = []
for char in s:
stack.append(char) # Push
reversed_s = ""
while stack:
reversed_s += stack.pop() # Pop until empty
return reversed_s
print(reverse_string("PyLearn")) # Output: nraeLyP