Notes on Queues in Data Structures
Introduction to Queues
- A queue is a FIFO (First In, First Out) data structure.
- Intuitive concept; prevalent in daily life (e.g., waiting in line).
Key Functions of Queues
- Enqueue: Adding an item to the end of the queue.
- Dequeue: Removing an item from the front of the queue.
Real-world Use Cases for Queues
- Situations where waiting occurs:
- Bank tellers
- Fast food orders (e.g., McDonald's)
- DMV customer service
- Supermarket checkout
- Important for modeling processes in computer programs.
Implementing Queues in Python
- Python has a built-in library called deque (double-ended queue).
- Allows adding/removing items from both ends.
- For simple queue operations, we focus on one end:
- Append for adding items.
- Pop left for removing items.
Importing deque
from collections import deque
Creating a Queue
- Create a new queue:
my_queue = deque()
.
- Adding items to the queue:
- Use
append()
function.
- Example:
my_queue.append(5)
my_queue.append(10)
Removing items from the Queue
- Use
popleft()
to dequeue:
- Example:
my_queue.popleft()
returns the first item (e.g., 5
).
Conclusion
- Simple implementation of a queue in Python through deque.
- As an exercise, try writing a wrapper class for deque to create a single-ended queue using push and pop as a stack.