Queue: First In, First Out Data Structure
A Queue is a data structure where the first data entered is the first one to be removed, following the First In, First Out (FIFO)
principle.
It operates similarly to standing in a queue in daily life, where data is processed in order.
Queues are used in situations like job scheduling, where several tasks are queued to be processed in the order they were requested, or in printer task queues.
Key Operations of Queue
Based on the FIFO principle, a queue offers the following key operations:
-
Enqueue
: Add an element to the back (tail) of the queue. The newly added element will occupy the last position in the queue. -
Dequeue
: Remove and return an element from the front (head) of the queue. Once removed, the next element occupies the new front. -
Peek or Front
: Check the element at the front of the queue. The checked element remains in place. -
IsEmpty
: Check if the queue is empty. ReturnsTrue
if there are no elements in the queue, otherwiseFalse
.
How is a Queue Implemented?
In Python, a simple queue can be implemented using a list. However, for efficiency, the deque
class from the collections
module is generally used.
deque
is a data structure that allows appending or popping elements from both ends efficiently.
# Importing the deque class from collections module from collections import deque # Create a queue queue = deque() # Enqueue operations queue.append('A') # Add A queue.append('B') # Add B # Dequeue operations print(queue.popleft()) # Output and remove 'A' print(queue.popleft()) # Output and remove 'B'
You can explore a more detailed example of implementing a queue using a Class
in the code editor on the right.
What is the most appropriate word to fill in the blank?
Guidelines
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result