Introduction
Imagine you have a stack of plates. You can only add a new plate on top or take the top plate off. This problem of managing items in a last-in, first-out order is solved by stack operations.
Think of a stack of books on a table. You add a new book on top (push), take the top book off to read (pop), or just look at the title of the top book without moving it (peek).
Stack (top) ┌─────┐ │ 3 │ <-- Peek shows this ├─────┤ │ 2 │ ├─────┤ │ 1 │ └─────┘ Operations: Push: Add new item on top Pop: Remove top item Peek: View top item
class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): if not self.items: return None return self.items.pop() def peek(self): if not self.items: return None return self.items[-1] stack = Stack() stack.push(1) stack.push(2) stack.push(3) print(stack.peek()) # Should print 3 print(stack.pop()) # Should print 3 print(stack.peek()) # Should print 2