Stack Implementation Using Linked List
A stack implemented using a linked list follows the LIFO (Last In First Out) principle. Unlike array implementation, linked list stacks dynamically allocate memory for each element and don't have size limitations (until memory is exhausted).
Algorithmic Steps
Core Operations
Initialize Stack
- Create a head pointer initialized to null.
- Optional: Maintain a size counter initialized to 0.
push()
- Create a new node with the given data.
- Set new node's next pointer to current head.
- Update head to point to the new node.
- Increment size counter (if maintained).
pop()
- Check if stack is empty (head is null).
- If empty, return "Stack Underflow".
- Store current head node in a temporary variabl.
- Update head to point to the next node.
- Decrement size counter (if maintained).
- Return data from the temporary node.
Utility Functions
peek()
- Check if stack is empty (head is null).
- If empty, return null.
- Return data from head node without removal.
isEmpty()
- Return true if head is null.
- Return false otherwise.
size()
- If size counter is maintained, return its value.
- Otherwise, traverse the list and count nodes.
Efficiency Analysis
Time Complexity
- Push/Pop/Peek:
O(1) - Search:
O(n)
Space Complexity
- Overall Space:
O(n) - Memory overhead:
(1 pointer per node)
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
Implementation Comparison
| 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 |
| Complexity | Slightly higher | Very Simple |