A stack is a linear data structure that follows the Last In First Out (LIFO) principle. This means that the last element added to the stack will be the first one to be removed.
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
print(f"Pushed {item} to the stack.")
def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
return "Stack is empty!"
def peek(self):
if not self.is_empty():
return self.stack[-1]
else:
return "Stack is empty!"
def is_empty(self):
return len(self.stack) == 0
def display(self):
print("Stack: ", self.stack)
# Example usage
my_stack = Stack()
my_stack.push(10)
my_stack.push(20)
my_stack.display()
print(f"Popped item: {my_stack.pop()}")
print(f"Top item: {my_stack.peek()}")
my_stack.display()