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.
Stack can be implemented using arrays or linked lists.
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.
Operation | Big-O Time |
---|---|
Push | O(1) |
Pop | O(1) |
Peek / Top | O(1) |
Real-World Applications of Stack
- Undo/Redo functionality in text editors
- Browser history
- Recursion
Advantages and Disadvantages of Stack
Advantages:
- Simple to implement and use, with O(1) time complexity for push and pop operations
- Efficient for certain algorithms (e.g., depth-first search)
- Useful for specific applications like recursion, expression evaluation, and backtracking
Disadvantages:
- Limited access to elements (only the top element is accessible)
- Fixed size if implemented using arrays (unless using dynamic arrays)
- Not suitable for random access of elements
- Can lead to underflow if popping from an empty stack
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 |PeekPushPop
Animation Controls
Stack Operations
Last updated on