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 like a line in everyday life, where elements are processed in the order they arrive.
Queues are used in scenarios such as job scheduling, where tasks are 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. ReturnsTrueif there are no elements in the queue, otherwiseFalse.
How is a Queue Implemented?
n Python, queues can be implemented using lists, but for better efficiency, the deque class from the collections module is recommended.
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 located on the right.
Lessons in this chapter Β· Introduction to Data Structures / Algorithms - Time Complexity, Space Complexity, Arrays, Stacks, Queues, Linked Lists, Hash Tables
- 1. The Core of Programming - Data Structures and Algorithms
- 2. What is Algorithm Complexity?
- 3. Time and Space Complexity of Algorithms
- 4. Storing Data Sequentially with Array
- 5. Coding Quiz - Implementing an Array
- 6. Stack: Data Entered Last Comes Out First
- 7. Coding Quiz - Implementing a Stack
- 8. Queue: First In, First Out Data Structure
- 9. Coding Quiz - Implementing a Queue
- 10. Creating a Linked List Structure Using Nodes
- 11. Coding Quiz - Implementing a Linked List
- 12. Storing Key-Value Pairs with Hash Table
- 13. Coding Quiz - Implementing a Hash Table
Which of the following is the most appropriate word to fill in the blank?
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help