QUEUES
A queue is a linear data structure that follows the First-In-First-Out (FIFO) principle, meaning that the first element added to the queue is the first one to be removed. It can be visualized as a line of people waiting for service, where new people join at the back of the line, and people are served or removed from the front of the line.
Operations on a Queue:
- Enqueue (or Push): Adding an element to the back (end) of the queue.
- Dequeue (or Pop): Removing the element from the front (beginning) of the queue.
- Peek (or Front): Returning the front element of the queue without removing it.
- isEmpty: Checking if the queue is empty.
- Size: Returning the number of elements in the queue.
Implementation of a Queue:
A queue can be implemented using various data structures such as arrays or linked lists. Here's an example implementation using a Python list:
class Queue:
def __init__(self):
self.items = []
def enqueue(self, item):
self.items.append(item)
def dequeue(self):
if not self.is_empty():
return self.items.pop(0)
def peek(self):
if not self.is_empty():
return self.items[0]
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
Example Usage:
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print(queue.peek()) # Output: 1
print(queue.dequeue()) # Output: 1
print(queue.size()) # Output: 2
Applications of Queues:
- Breadth-First Search (BFS): Used in graph traversal algorithms like BFS to explore nodes level by level.
- Task Scheduling: Used in operating systems to schedule tasks and processes for execution.
- Print Queue: Used in printers to manage printing tasks in the order they are received.
- Message Queues: Used in messaging systems to buffer messages between producers and consumers.
- Waiting Lines: Used in simulations to model waiting lines in systems like traffic flow and customer service.
Queues are essential data structures with various applications in computer science, software engineering, and everyday life. They provide efficient operations and are used in many algorithms and systems for managing data and controlling flow.