Write a program to implement Stacks.
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
"""Adds an item to the top of the stack."""
self.stack.append(item)
print(f"Pushed: {item}")
def pop(self):
"""Removes and returns the top item. Returns None if empty."""
if self.is_empty():
print("Stack Underflow: Cannot pop from an empty stack.")
return None
return self.stack.pop()
def peek(self):
"""Returns the top item without removing it."""
if self.is_empty():
return None
return self.stack[-1]
def is_empty(self):
"""Checks if the stack is empty."""
return len(self.stack) == 0
# Usage
s = Stack()
s.push(10)
s.push(20)
print(f"Popped: {s.pop()}") # Returns 20
print(f"Top element: {s.peek()}") # Returns 10
Comments
Post a Comment