Queue Data Structure: Definition, How It Works, and Uses
queue is a data structure that stores items in a First-In-First-Out (FIFO) order, meaning the first element added is the first one removed. It works like a real-life line where people wait their turn, allowing insertion at the back and removal from the front.How It Works
A queue works like a line at a ticket counter or a grocery store checkout. The first person who gets in line is the first to be served and leave the line. Similarly, in a queue data structure, the first item added is the first one to be removed.
Items are added at the back (called enqueue) and removed from the front (called dequeue). This keeps the order fair and predictable. Unlike a stack where you add and remove from the same end, a queue keeps a strict order of processing.
Example
This example shows a simple queue using Python's collections.deque which efficiently supports adding and removing items from both ends.
from collections import deque queue = deque() # Add items to the queue queue.append('apple') queue.append('banana') queue.append('cherry') print('Queue after adding:', list(queue)) # Remove items from the queue first_item = queue.popleft() print('Removed item:', first_item) print('Queue after removing:', list(queue))
When to Use
Queues are useful when you need to process things in the exact order they arrive. For example:
- Handling tasks in print queues where documents print in order.
- Managing requests in web servers to serve users fairly.
- Simulating real-world lines like customer service or call centers.
- In algorithms like breadth-first search where nodes are explored level by level.
Using a queue ensures fairness and order in processing.
Key Points
- A queue follows First-In-First-Out (FIFO) order.
- Items are added at the back and removed from the front.
- It models real-world lines and fair processing.
- Common operations are enqueue (add) and dequeue (remove).
- Used in many practical applications like task scheduling and breadth-first search.