What is a Stack?
A Stack is a linear data structure that operates on the LIFO principle. Think of it like a stack of books - you can only add or remove books from the top of the pile. The last book you place on top is the first one you'll take off.
Use Cases for Stacks
The Stack data structure follows the Last-In-First-Out (LIFO) principle, making it ideal for:
- Function call management: Tracking function calls and returns in programming languages
- Undo operations: Implementing undo functionality in text editors and applications
- Browser history: Managing back button functionality in web browsers
- Backtracking algorithms: Solving puzzles like mazes, N-Queens problem
- Memory management: Managing local variables and function parameters
Key Operations
The stack operations are implemented progressively to show how each method builds upon the basic structure.
1. Initialize the Stack
The foundation of any stack is its initialization. We create an empty list to hold our stack elements, which will grow and shrink as we add and remove items.
class Stack:
def __init__(self):
self.items = []
2. Push an Element
The push operation adds a new element to the top of the stack. This is the primary way to insert data into a stack. Think of it like placing a new book on top of a pile - the new item becomes the most recently added element and will be the first one accessed.
class Stack:
def __init__(self):
self.items = []
def push(self, data):
"""Add an element to the top of the stack"""
self.items.append(data)
3. Pop Operation
The pop operation removes and returns the top element from the stack. This follows the LIFO principle - the last item pushed is the first one to be popped. It's like taking the top book from a pile. The method both removes the element from the stack and gives it back to you.
class Stack:
def __init__(self):
self.items = []
def push(self, data):
"""Add an element to the top of the stack"""
self.items.append(data)
def pop(self):
"""Remove and return the top element"""
return self.items.pop()
4. Peek Operation
The peek operation allows you to look at the top element without removing it from the stack. This is useful when you need to check what's on top before deciding whether to pop it or perform other operations. It's like looking at the title of the top book without picking it up.
class Stack:
def __init__(self):
self.items = []
def push(self, data):
"""Add an element to the top of the stack"""
self.items.append(data)
def pop(self):
"""Remove and return the top element"""
return self.items.pop()
def peek(self):
"""View the top element without removing it"""
return self.items[-1]
5. Additional Helper Methods
These utility methods enhance the stack's functionality by providing information about its state and a way to display its contents.
class Stack:
def __init__(self):
self.items = []
def push(self, data):
"""Add an element to the top of the stack"""
self.items.append(data)
def pop(self):
"""Remove and return the top element"""
return self.items.pop()
def peek(self):
"""View the top element without removing it"""
return self.items[-1]
def is_empty(self):
"""Check if the stack is empty"""
return self.items == []
def __len__(self):
"""Return the size of the stack"""
if not self.items:
return None
return len(self.items)
def __repr__(self):
"""Display stack from top to bottom"""
if not self.items:
return ""
return '\n'.join([f"{i}" for i in self.items[::-1]])