This Python program implements a basic stack data structure with the following operations:
is_empty(): Checks if the stack is empty.push(item): Pushes an item onto the stack.pop(): Pops (removes and returns) an item from the stack.peek(): Returns the top item of the stack without removing it.size(): Returns the size (number of elements) of the stack.
In computer science, a stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle. It operates like a stack of items, where the last item added is the first one to be removed. Stacks are commonly used in various algorithms and applications, such as managing function calls in programming languages, parsing expressions, and more.
Problem Statement
Implement a stack data structure in Python with basic operations like push, pop, and peek (view the top element), and demonstrate how it works.
Python Program to Implement Stack
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
else:
return None # Stack is empty
def peek(self):
if not self.is_empty():
return self.items[-1]
else:
return None # Stack is empty
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
# Example usage
if __name__ == "__main__":
stack = Stack()
print("Stack is empty:", stack.is_empty()) # Output: Stack is empty: True
stack.push(5)
stack.push(10)
stack.push(15)
print("Stack size:", stack.size()) # Output: Stack size: 3
print("Top element:", stack.peek()) # Output: Top element: 15
popped_item = stack.pop()
print("Popped item:", popped_item) # Output: Popped item: 15
print("Stack size after pop:", stack.size()) # Output: Stack size after pop: 2
How It Works
- The
Stackclass is defined with methodspush,pop,peek,is_empty, andsizeto manage the stack operations. - The
pushmethod appends an item to the end of the list, simulating the action of pushing onto the stack. - The
popmethod removes and returns the last item in the list, simulating the action of popping from the stack. - The
peekmethod returns the last item in the list without removing it, allowing you to view the top element. - The
is_emptymethod checks if the stack is empty by examining the length of the list. - The
sizemethod returns the number of elements in the stack. - Example usage demonstrates creating a stack, performing operations, and printing the results.
Input/Output
