Queue

Queue data structure and its operations

A queue is a linear data structure that follows the First In, First Out (FIFO) principle. This means that the element added first will be the first one to be removed, much like a line at a checkout counter.

Key Characteristics

  • FIFO Principle: Elements are removed in the order they were added.
  • Two main operations:
    • Enqueue: Adds an element to the end of the queue.
    • Dequeue: Removes an element from the front of the queue.

Types of Queues

  • Simple Queue: Basic queue with FIFO order.
  • Circular Queue: Connects the end of the queue back to the front, allowing for better utilization of memory.
  • Priority Queue: Elements are dequeued based on priority, not just on the order they were enqueued.
  • Deque (Double-Ended Queue): Allows insertion and deletion from both ends.

Applications of Queue

  • Scheduling tasks: Like printer job management.
  • Handling requests: Web servers use queues to handle client requests in order.
  • Breadth-First Search (BFS): In graph traversal and other algorithms.

Example (in Python)

from collections import deque

# Initialize a queue
queue = deque()

# Enqueue elements
queue.append("a")
queue.append("b")
queue.append("c")

# Dequeue elements
print(queue.popleft())  # Output: "a"
print(queue.popleft())  # Output: "b"

This implementation uses Python’s deque from the collections module, which efficiently supports queue operations.

Resources