Here is the code.
class Stack:
def __init__(self, capacity):
self.capacity = capacity
self.stack = []
def push(self, item):
if len(self.stack) < self.capacity:
self.stack.append(item)
else:
print("Stack overflow error")
def pop(self):
if self.stack:
return self.stack.pop()
else:
print("Stack underflow error")
return None
def peek(self):
if self.stack:
return self.stack[-1]
else:
print("Stack is empty")
return None
# Example usage:
stack = Stack(3) # Create a stack with capacity 3
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4) # This will cause a stack overflow error
print(stack.peek()) # Output: 3
print(stack.pop()) # Output: 3
print(stack.pop()) # Output: 2
print(stack.pop()) # Output: 1
print(stack.pop()) # This will cause a stack underflow error
This example demonstrates how a stack's fixed size can lead to overflow and underflow errors, and its LIFO nature affects operations like pop and peek.