A queue is a linear data structure in computer science that follows the First-In-First-Out (FIFO) principle. In a queue, the first element added is the first one to be removed. Think of it as a line of people waiting in a queue, where the person who arrived first is served first.
Key operations and characteristics of a queue:
Enqueue (Push): Adding an element to the back (rear) of the queue.
Dequeue (Pop): Removing and retrieving the element from the front (front) of the queue.
Front (Peek): Retrieving the element from the front of the queue without removing it.
Rear: Retrieving the element from the back of the queue without removing it.
Empty Check: Checking if the queue is empty.
Common use cases and applications of queues:
Breadth-First Search (BFS): Queues are used to implement BFS in graph traversal algorithms. BFS explores neighbors of nodes level by level.
Print Queue: Managing print jobs in the order they were received.
Task Scheduling: Queues are used in task scheduling systems to manage the execution of tasks in a fair and orderly manner.
Bounded Buffers: In producer-consumer scenarios, where data is produced by one process and consumed by another, queues can be used to buffer data.
Caching: In web applications, caching systems may use queues to store recently used data and remove the least recently used data.
Call Center Systems: Queues can be used to manage incoming calls and assign them to available agents.
Implementing a queue can be done using arrays or linked lists. Here's a simple example of implementing a queue using Python's built-in list:
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def enqueue(self, item):
self.items.append(item)
def dequeue(self):
if not self.is_empty():
return self.items.pop(0)
else:
raise Exception("Queue is empty")
def front(self):
if not self.is_empty():
return self.items[0]
else:
raise Exception("Queue is empty")
def rear(self):
if not self.is_empty():
return self.items[-1]
else:
raise Exception("Queue is empty")
def size(self):
return len(self.items)
# Example usage
queue = Queue()
print("Is the queue empty?", queue.is_empty()) # True
queue.enqueue(5)
queue.enqueue(10)
queue.enqueue(7)
print("Front:", queue.front()) # 5
print("Rear:", queue.rear()) # 7
print("Size:", queue.size()) # 3
dequeued_item = queue.dequeue()
print("Dequeued item:", dequeued_item) # 5
print("Size after dequeue:", queue.size()) # 2
print("Is the queue empty?", queue.is_empty()) # False
This example demonstrates a basic queue implementation in Python using a list. However, keep in mind that for more efficient queue operations, especially dequeues in larger queues, using a collections.deque or implementing a queue with a linked list can be more optimal.