Queue
Explore the ins and outs of queue data structures in our latest blog post. From understanding the fundamentals to advanced techniques, discover how to leverage queue for optimal efficiency in your coding projects.
Series: Data Structures
Episodes: (2/6)
Introduction
A queue is a fundamental data structure in computer science that follows the First-In-First-Out (FIFO) principle. In a queue, elements are added at the rear and removed from the front, resembling a line of people waiting for a service where the first person to join the line is the first to be served. This characteristic makes it particularly useful for modeling scenarios where the order of arrival matters, such as task scheduling, process management, and network packet handling.
Available Operations
- Enqueue (or Offer): Adding an element to the rear (end) of the queue.
- Dequeue (or Poll): Removing the element from the front (beginning) of the queue.
- Peek (or Front): Viewing the element at the front of the queue without removing it.
- IsEmpty: Checking if the queue is empty.
- IsFull (in bounded queues): Checking if the queue has reached its maximum capacity.
Implementation
// Define a generic class for the queue
class Queue<T> {
private items: T[]; // Array to store the queue elements
constructor() {
this.items = []; // Initialize the queue as an empty array
}
// Add element to the end of the queue
enqueue(element: T): void {
this.items.push(element); // Add element to the end of the array
}
// Remove and return the front element from the queue
dequeue(): T | undefined {
return this.items.shift(); // Remove and return the first element of the array
}
// Return the front element of the queue without removing it
front(): T | undefined {
return this.items[0]; // Return the first element of the array
}
// Check if the queue is empty
isEmpty(): boolean {
return this.items.length === 0; // If the length of the array is 0, queue is empty
}
// Return the number of elements in the queue
size(): number {
return this.items.length; // Return the length of the array
}
// Clear the queue
clear(): void {
this.items = []; // Clear the array by assigning it to an empty array
}
}
Usage
const queue = new Queue<number>(); // Create a queue of numbers
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
console.log("Queue size:", queue.size()); // Output: 3
console.log("Front element:", queue.front()); // Output: 1
console.log("Dequeue:", queue.dequeue()); // Output: 1
console.log("Queue size after dequeue:", queue.size()); // Output: 2
console.log("Is queue empty?", queue.isEmpty()); // Output: false
queue.clear();
console.log("Is queue empty after clearing?", queue.isEmpty()); // Output: true