What is Stack Implementation Using Linked List?
Building a stack with a linked list instead of an array gets you the same LIFO (Last In, First Out) behavior, but without a fixed capacity: every push allocates a fresh node, so the stack can keep growing as long as memory allows.
Initialize
A top pointer is created and set to null, meaning there are no nodes yet. Some implementations also keep a size counter, initialized to 0, so size() doesn't need to walk the whole list.
push()
A new node is created pointing to whatever top currently points to, then top is repointed to the new node. Nothing else in the list is touched, which is why this runs in O(1).
↓ push(7) ↓
pop()
If top is null there's nothing to remove, so pop reports "Stack Underflow". Otherwise the data at top is saved, top is moved to point at the next node, and the saved data is returned. The old top node itself is left for garbage collection.
↓ pop() → returns 7 ↓
peek()
Returns the data at the top node without moving the top pointer, so the stack is left exactly as it was. If top is null, it returns null instead.
isEmpty() & size()
isEmpty() is just a null check on top. size() is O(1) if a counter is maintained on every push/pop, or O(n) if it has to walk the whole list counting nodes instead.
isEmpty() → true
Time Complexity
| Operation | Complexity |
|---|---|
| push() | O(1) |
| pop() | O(1) |
| peek() | O(1) |
| isEmpty() | O(1) |
| size() | O(1) or O(n) |
Key Characteristics
- Dynamic Size: No fixed capacity (grows as needed)
- Memory Efficiency: Uses only needed memory
- No Wasted Space: Unlike array implementation
- Extra Memory: Requires space for pointers
- Flexibility: Can grow until memory exhausted
Linked List vs Array Implementation
| Feature | Linked List | Array |
|---|---|---|
| Memory Usage | Extra for pointers | Fixed size, may be wasted |
| Dynamic Size | Yes | No (unless resized) |
| Memory Allocation | Dynamic | Static (usually) |
| Access Time | O(1) for top | O(1) for all |
| Implementation Complexity | Slightly more complex | Simpler |