Stack: Array Implementation
Explore how a stack data structure works using array implementation. Watch push, pop, and peek operations in action with LIFO (Last In, First Out) principle.
Interactive Operations
Array Implementation
O(1) Operations
Stack Visualization
0
1
2
3
4
5
6
7
Size: 0 / 8
Status: Empty
Current Step:
Select an operation to begin visualization
Complexity Analysis
O(1)
Push
O(1)
Pop
O(1)
Peek
O(n) Space
Fixed array allocation
Stack Operations
Push
Add element to the top of stack
Pop
Remove and return top element
Peek/Top
View top element without removing
Applications
• Function Calls: Managing function call stack
• Undo Operations: Ctrl+Z functionality
• Expression Evaluation: Parsing mathematical expressions
• Browser History: Back button functionality
• Syntax Checking: Matching parentheses/brackets
Implementation
class StackArray:
def __init__(self, max_size):
self.array = [None] * max_size # Fixed-size array
self.top = -1 # Index of top element
self.max_size = max_size # Maximum capacity
def push(self, value):
# Check for stack overflow
if self.top >= self.max_size - 1:
raise Exception("Stack Overflow")
# Increment top and add element
self.top += 1
self.array[self.top] = value
return value
def pop(self):
# Check for stack underflow
if self.top < 0:
raise Exception("Stack Underflow")
# Get top element and decrement top
value = self.array[self.top]
self.array[self.top] = None # Optional: clear the slot
self.top -= 1
return value
def peek(self):
# Check if stack is empty
if self.top < 0:
raise Exception("Stack is Empty")
return self.array[self.top]
def is_empty(self):
return self.top < 0
def is_full(self):
return self.top >= self.max_size - 1
def size(self):
return self.top + 1