Skip to Content

Stack

What is Stack?

Stack is a Last In First Out (LIFO) data structure, meaning that the last element added will be the first element to be removed.

Key operations of a stack include:

  • Push: Add an element to the top of the stack.
  • Pop: Remove and return the top element of the stack.
  • Peek: Return the top element without removing it.
OperationBig-O Time
PushO(1)
PopO(1)
Peek / TopO(1)

Stack Class Implementation

stack.py
class Stack: def __init__(self) -> None: self.items = [] def __len__(self) -> int: return len(self.items) def __str__(self) -> str: return str(self.items) def is_empty(self) -> bool: return len(self.items) == 0 def push(self, item: int) -> None: self.items.append(item) def pop(self) -> int: if self.is_empty(): raise IndexError("Stack Underflow: Cannot pop from an empty stack") return self.items.pop() def peek(self) -> int: if self.is_empty(): raise IndexError("Stack Underflow: Cannot pop from an empty stack") return self.items[-1] stack = Stack() stack.push(1) stack.push(2) stack.push(3) print(len(stack)) print(stack) print(stack.pop()) print(stack.peek()) print(stack)

Stack Visualization

Stack Visualization
Top → 0x5008
0x5000
42
0x5004
17
0x5008
89
← TOP
Stack Size: 3 |
Peek
Push
Pop
Animation Controls
Stack Operations
Last updated on