class Stack:
def __init__(self):
self.items = []
def push(self, item):
# Add an item to the top of the stack
self.items.append(item)
def pop(self):
# Remove and return the top item of the stack
if not self.is_empty():
return self.items.pop()
return None
def peek(self):
# Return the top item of the stack without removing it
if not self.is_empty():
return self.items[-1]
return None
def is_empty(self):
# Check if the stack is empty
return len(self.items) == 0
def size(self):
# Return the size of the stack
return len(self.items)
### Deque-based Stack
from collections import deque
class Stack:
def __init__(self):
self.items = deque()
def push(self, item):
# Add an item to the top of the stack
self.items.append(item)
def pop(self):
# Remove and return the top item of the stack
if not self.is_empty():
return self.items.pop()
return None
def peek(self):
# Return the top item of the stack without removing it
if not self.is_empty():
return self.items[-1]
return None
def is_empty(self):
# Check if the stack is empty
return len(self.items) == 0
def size(self):
# Return the size of the stack
return len(self.items)
## Complexity Analysis
### List-based Stack
- **Push**: O(1)
- **Pop**: O(1)
- **Peek**: O(1)
- **Space Complexity**: O(n)
### Deque-based Stack
- **Push**: O(1)
- **Pop**: O(1)
- **Peek**: O(1)
- **Space Complexity**: O(n)
## Edge Cases
- **Empty Stack**: Ensure `pop` and `peek` handle empty stacks gracefully.
- **Large Data**: Test with large datasets to ensure performance remains optimal.
## Testing
### Test Cases
1. Push and pop elements to/from the stack.
2. Peek the top element.
3. Check if the stack is empty.
4. Measure performance with large datasets.
### Example Tests
def test_stack():
stack = Stack()
assert stack.is_empty() == True
stack.push(1)
stack.push(2)
assert stack.peek() == 2
assert stack.pop() == 2
assert stack.pop() == 1
assert stack.is_empty() == True
test_stack()
## Thinking and Problem-Solving Tips
- Understand the LIFO property of stacks.
- Practice implementing stacks using different data structures.
- Test with various edge cases to ensure robustness.
## Conclusion
Stacks are a versatile data structure with numerous applications. Understanding their implementation and optimization is crucial for efficient problem-solving in computer science.
## Additional Resources
- [Python Documentation on Collections](https://docs.python.org/3/library/collections.html)
- [LeetCode Stack Problems](https://leetcode.com/tag/stack/)
- [GeeksforGeeks Stack Tutorial](https://www.geeksforgeeks.org/stack-data-structure/)
By mastering stacks, you can enhance your problem-solving skills and tackle a wide range of computational problems effectively. Happy coding!
Our interactive tutorials and AI-assisted learning will help you master problem-solving skills and teach you the algorithms to know for coding interviews.
Start Coding for FREE