-
Description:
A stack is a linear data structure that follows the Last In, First Out (LIFO) principle.
-
Create a Stack:
You can use a list in Python to simulate a stack.
-
Push Operation:
Add an element to the top of the stack.
-
Pop Operation:
Remove the top element from the stack.
-
Peek Operation:
View the top element of the stack without removing it.
-
Check if Stack is Empty:
Verify if the stack contains any elements.
-
Size Operation:
Check the number of elements in the stack.
- class Stack:
def __init__(self):
self.stack = []
def push(self, value):
self.stack.append(value)
print(f"{value} pushed to stack")
def pop(self):
if self.is_empty():
return "Stack is empty"
return self.stack.pop()
def peek(self):
if self.is_empty():
return "Stack is empty"
return self.stack[-1]
def is_empty(self):
return len(self.stack) == 0
def size(self):
return len(self.stack)
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)
print("Top element:", stack.peek())
print("Popped element:", stack.pop())
print("Is stack empty?", stack.is_empty())
print("Stack size:", stack.size())