Stacks and queues are fundamental data structures in computer science that organize and manage data efficiently. They differ in how elements are added and removed, following distinct principles: LIFO (Last In First Out) for stacks and FIFO (First In First Out) for queues. Python provides simple ways to implement these structures using lists.
A stack follows the LIFO principle, meaning that the last element added to the stack is the first one to be removed. It is commonly used in scenarios like parsing, evaluating expressions, and backtracking algorithms.
• Push: Adds an element to the top of the stack.
• Pop: Removes the element from the top of the stack.
• Peek/Top: Retrieves the top element without removing it (optional in Python list).
• IsEmpty: Checks if the stack is empty.
# Stack implementation using Python list
stack = []
# Push elements onto the stack
stack.append(10)
stack.append(20)
stack.append(30)
print("Stack after push:", stack) # Output: [10, 20, 30]
# Pop elements from the stack
stack.pop()
print("Stack after pop:", stack) # Output: [10, 20]
# Check the top element
top_element = stack[-1]
print("Top element:", top_element) # Output: 20
# Check if the stack is empty
is_empty = len(stack) == 0
print("Is stack empty?", is_empty) # Output: False
• LIFO principle is followed.
• Operations (push/pop) occur at the top of the stack.
• Insertion order is preserved.
• Duplicate values are allowed.
A queue follows the FIFO principle, where the first element added to the queue is the first one to be removed. Queues are widely used in scheduling algorithms, breadth-first search (BFS), and task processing.
• Enqueue: Adds an element to the rear (end) of the queue.
• Dequeue: Removes the element from the front of the queue.
• Peek/Front: Retrieves the front element without removing it (optional).
• IsEmpty: Checks if the queue is empty.
# Queue implementation using Python list
queue = []
# Enqueue elements into the queue
queue.append(10)
queue.append(20)
queue.append(30)
print("Queue after enqueue:", queue) # Output: [10, 20, 30]
# Dequeue elements from the queue
queue.pop(0)
print("Queue after dequeue:", queue) # Output: [20, 30]
# Check the front element
front_element = queue[0]
print("Front element:", front_element) # Output: 20
# Check if the queue is empty
is_empty = len(queue) == 0
print("Is queue empty?", is_empty) # Output: False
• FIFO principle is followed.
• Operations (enqueue/dequeue) occur at opposite ends of the queue.
• Insertion order is preserved.
• Duplicate values are allowed.
• Stack is useful for:
‣ Parsing operations.
‣ Undo/Redo functionality in text editors.
‣ Expression evaluation (e.g., converting infix to postfix).
‣ Backtracking algorithms (e.g., maze solvers).
• Queue is useful for:
‣ CPU scheduling.
‣ Task management systems.
‣ Implementing breadth-first search (BFS).
‣ Resource sharing between multiple users (e.g., printer queues).