1. Introduction
A queue is a fundamental data structure that operates on a First In First Out (FIFO) principle. It has two main operations: enqueue (to add items to the back) and dequeue (to remove items from the front). In this guide, we'll build a basic queue in TypeScript, taking advantage of its type-checking features.
2. Program Overview
Our queue will support the following operations:
1. enqueue: Add an element to the back of the queue.
2. dequeue: Remove and return the front element of the queue.
3. peek: View the front element without removing it.
4. isEmpty: Check if the queue is empty.
5. size: Get the number of elements in the queue.
We'll use an array to facilitate our queue implementation and TypeScript interfaces to guarantee type consistency.
3. Code Program
// Define the Queue class and its methods
class Queue<T> {
private items: T[] = []; // Initialize an empty array to store queue items
// Adds a new item to the back of the queue
enqueue(element: T): void {
this.items.push(element);
}
// Removes and returns the front item from the queue
dequeue(): T | undefined {
return this.items.shift();
}
// Views the front item without removing it
peek(): T | undefined {
return this.items[0];
}
// Determines if the queue is empty
isEmpty(): boolean {
return this.items.length === 0;
}
// Returns the number of elements in the queue
size(): number {
return this.items.length;
}
}
// Test the Queue class
const numberQueue = new Queue<number>();
console.log("Enqueue 3 to the queue");
numberQueue.enqueue(3);
console.log("Enqueue 7 to the queue");
numberQueue.enqueue(7);
console.log(`Front element: ${numberQueue.peek()}`);
console.log(`Dequeued element: ${numberQueue.dequeue()}`);
console.log(`Queue size: ${numberQueue.size()}`);
Output:
Enqueue 3 to the queue Enqueue 7 to the queue Front element: 3 Dequeued element: 3 Queue size: 1
4. Step By Step Explanation
1. We begin by declaring a generic Queue class. The <T> notation indicates that this class can be used with any type T, such as numbers, strings, or custom objects.
2. Inside the class, we have a private array called items that will contain the contents of our queue.
3. The enqueue method is utilized to append an item to the end of the items array.
4. The dequeue method extracts and returns the first item from the items array, signifying the front of the queue.
5. Using the peek method, we can view the front item without removing it from the queue.
6. The isEmpty method is designed to check if the queue contains any items.
7. The size method indicates the total number of items currently in the queue.
8. We end the program by testing our queue with a few numbers, illustrating the FIFO behavior as we enqueue and dequeue items.
Comments
Post a Comment
Leave Comment