[ADS-FINAL-PREP] 4. Queue
A Queue is a data structure that operates on the FIFO (First In, First Out) principle, meaning "first in, first out." It resembles a real-life line at a store: the first person to join the queue is the first to be served.
Basic Queue Operations
- enqueue(x) — Adds element
xto the end (rear) of the queue.
- dequeue() — Removes and returns the element from the front of the queue.
- front() / peek() — Views the first element without removing it.
- is_empty() — Checks whether the queue is empty.
- size() — Returns the number of elements in the queue.
Implementation Approaches
A queue can be implemented in several ways:
- Array-based (list in Python):
- Simple method, but operations can be slow due to the need to shift elements.
- Using Two Stacks:
- Often used in algorithmic problems to optimize operations.
- Linked List-based:
- Fast implementation without the need to shift elements.
- Built-in Structures:
- In Python —
collections.dequeorqueue.Queue.
Use Cases
Queues are applied in the following scenarios:
- Task Scheduling: (e.g., CPU task execution).
- Data Processing: (e.g., streaming data reading).
- Real-world Modeling: (e.g., customer queues in a bank or shop).
- Graph Algorithms: (e.g., BFS — Breadth-First Search).
Advantages of a Queue
- Simplicity of implementation.
- High efficiency of operations (when shifting elements is not required, unlike plain dynamic lists).
Disadvantages of a Queue
- Restricted access: You can only interact with the front and rear of the queue.
- Fixed capacity: If implemented using a standard array, it may be limited in size.
If you noticed a mistake or copyright issues, please contact: lebroskiofficial@proton.me