DSA Notes
Complete implementations of stacks in three ways — dynamic array (Python list), fixed-size array, and singly linked list. Each implementation handles all edge cases with error checking, includes performance analysis, and discusses when to choose each approach.
Implementation 1 — Dynamic Array Stack
The most practical implementation for most use cases.
Implementation 3 — Linked List Stack
When you need guaranteed O(1) (not just amortized) for every push and pop.
class _Node:
__slots__ = ('data', 'next') # Memory optimization
def __init__(self, data):
self.data = data
self.next = None
class LinkedListStack:
"""
Stack using singly linked list.
head = top of stack → guaranteed O(1) push and pop (no amortized).
"""
def __init__(self):
self._top = None # Linked list head
self._size = 0
def push(self, item) -> None:
"""O(1) guaranteed."""
node = _Node(item)
node.next = self._top
self._top = node
self._size += 1
def pop(self):
"""O(1) guaranteed."""
if self.is_empty():
raise IndexError("Stack underflow")
item = self._top.data
self._top = self._top.next
self._size -= 1
return item
def peek(self):
"""O(1) guaranteed."""
if self.is_empty():
raise IndexError("Stack underflow")
return self._top.data
def is_empty(self) -> bool:
return self._top is None
def size(self) -> int:
return self._size
def to_list(self) -> list:
"""Convert to list from top to bottom. O(n)."""
result = []
current = self._top
while current:
result.append(current.data)
current = current.next
return result
def __repr__(self) -> str:
if self.is_empty():
return "LinkedStack(empty)"
return "LinkedStack(top→bottom): " + " → ".join(map(str, self.to_list()))Comparison of Three Implementations
| Feature | Dynamic Array | Fixed Array | Linked List |
|---|---|---|---|
| Push | O(1) amortized | O(1) always | O(1) always |
| Pop | O(1) | O(1) | O(1) |
| Peek | O(1) | O(1) | O(1) |
| Memory per element | ~8 bytes (8B ref) | ~8 bytes (pre-alloc) | ~24 bytes (data + ptr) |
| Max size | Unlimited (RAM) | Fixed at creation | Unlimited (RAM) |
| Overflow possible | No (until RAM full) | Yes (at capacity) | No |
| Cache performance | Excellent | Excellent | Poor |
| Memory wasted | Some (over-alloc) | Yes (pre-alloc) | None |
| Best for | General use | Known max size | Real-time systems |
Two Stacks in One Array
A classic interview problem: implement two stacks using a single array efficiently.
Stack with Minimum Element — O(1)
Java Stack Implementation
For completeness, the standard Java approach:
// Using Java's built-in Deque as a stack (preferred over legacy Stack class)
import java.util.ArrayDeque;
import java.util.Deque;
Deque<Integer> stack = new ArrayDeque<>();
// Push
stack.push(1); // or stack.addFirst(1)
// Pop
int top = stack.pop(); // or stack.removeFirst()
// Peek
int peek = stack.peek(); // or stack.peekFirst()
// Check empty
boolean empty = stack.isEmpty();
// Size
int size = stack.size();
// Why Deque instead of Stack?
// Java's legacy Stack class is synchronized (thread-safe but slow).
// ArrayDeque is faster and is the modern standard for stacks in Java.Summary
Three implementations for different needs:
- Dynamic Array Stack (Python list): General-purpose, simplest code, excellent cache performance — use by default
- Fixed Array Stack: When maximum size is known and memory must be bounded — embedded systems, OS kernels
- Linked List Stack: When guaranteed O(1) (not amortized) is required — real-time systems
Special-purpose stacks:
- Two Stacks in One Array: Efficient space sharing when you need exactly two stacks
- Min Stack: Supports O(1) minimum query using a parallel min-tracking stack
*Next Lesson: Stack Using Arrays — Deep dive into array-backed stacks with memory layout, capacity management, and performance.*
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Stack Implementation — Three Complete Implementations with Edge Cases.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Data Structures & Algorithms topic.
Search Terms
data-structures-algorithms, data structures & algorithms, data, structures, algorithms, stacks, stack, implementation
Related Data Structures & Algorithms Topics