Standing in Line, Queue
A Queue
is a data structure that resembles standing in line.
Just as the person who stands in line first gets served first, in a queue, the data that comes in first is processed first.
Due to this structure, a queue follows the principle of FIFO (First In, First Out)
, meaning "first in, first out."
How are queues used?
-
Printer job queue: A printer processes print jobs in the order they were received.
-
Call center queue: When a customer calls, they are added to a queue, and when an agent becomes free, they start by assisting the customer who has been waiting the longest.
Key Operations of a Queue
The key operations frequently used with a queue are as follows:
-
enqueue: The operation to
add
new data to the end of the queue. -
dequeue: The operation to
remove and return
data from the front of the queue. -
peek: The operation to
check
the data at the front of the queue without removing it. -
is_empty: The operation to check if the queue is
empty
.
Implementing a Queue in Python
By using the append()
method to add data and the pop(0)
method to remove data, a basic queue can be implemented with a list.
class Queue:
# Initialize the queue
def __init__(self):
self.queue = []
# Add data to the queue
def enqueue(self, item):
self.queue.append(item)
print(f"Enqueue: {item} has been added to the queue.")
# Remove data from the queue
def dequeue(self):
if not self.is_empty():
item = self.queue.pop(0)
print(f"Dequeue: {item} has been removed from the queue.")
return item
else:
print("Dequeue: The queue is empty.")
return None
# Check the data at the front of the queue
def peek(self):
if not self.is_empty():
return self.queue[0]
else:
print("Peek: The queue is empty.")
return None
# Check if the queue is empty
def is_empty(self):
return len(self.queue) == 0
# Queue usage example
my_queue = Queue()
my_queue.enqueue(1) # Enqueue: 1 has been added to the queue.
my_queue.enqueue(2) # Enqueue: 2 has been added to the queue.
print(f"Peek: The item at the front of the queue is {my_queue.peek()}.")
my_queue.dequeue() # Dequeue: 1 has been removed from the queue.
my_queue.dequeue() # Dequeue: 2 has been removed from the queue.
my_queue.dequeue() # The queue is empty, cannot remove item.
In Summary
-
A queue is a data structure that follows the
FIFO (First In, First Out)
principle. -
Key operations include enqueue (add), dequeue (remove), peek (check data), and is_empty (check if empty).
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.