Queue Data Structure

JavaScript

What is Queue data structure?

A queue is a linear data structure that follows the First In, First Out (FIFO) principle. In a queue, elements are added at the rear (also known as enqueue) and removed from the front (also known as dequeue). This ensures that the oldest element in the queue is the first one to be removed.

Key features of a queue:

1. FIFO Principle: The element that is added first will be the first one to be removed.

2. Insertion (Enqueue): Elements are added to the rear end of the queue.

3. Deletion (Dequeue): Elements are removed from the front end of the queue.

4. Support for Other Operations: Apart from enqueue and dequeue, queues may support other operations like peek (to view the front element without removing it) and isEmpty (to check if the queue is empty).

Note: A real-world analogy for a queue can be seen in situations like waiting in line at a ticket counter or at a checkout in a supermarket 😁

Implement a Queue data structure in JavaScript:

Here's an implementation of a Queue data structure in JavaScript.

js Copy Code
class Queue {
  constructor() {
    this.items = [];
  }

  // Adding element to the queue
  enqueue(element) {
    this.items.push(element);
  }

  // Removing element from the queue
  dequeue() {
    if (this.isEmpty()) {
      return "Underflow";
    }
    return this.items.shift();
  }

  // Returns the front element of the queue
  front() {
    if (this.isEmpty()) {
      return "No elements in Queue";
    }
    return this.items[0];
  }

  // Checks if the queue is empty
  isEmpty() {
    return this.items.length === 0;
  }

  // Returns the size of the queue
  size() {
    return this.items.length;
  }

  // Prints the elements of the queue
  printQueue() {
    let str = "";
    for (let i = 0; i < this.items.length; i++) {
      str += this.items[i] + " ";
    }
    return str;
  }
}

// Example usage:
const queue = new Queue();
console.log(queue.isEmpty()); // true
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.enqueue(40);
console.log(queue.printQueue()); // 10 20 30 40
console.log(queue.front()); // 10
console.log(queue.dequeue()); // 10
console.log(queue.printQueue()); // 20 30 40
console.log(queue.size()); // 3
Output:
true
10 20 30 40 
10
10
20 30 40 
3

This implementation follows the basic principles of a queue:

enqueue(element): Adds an element to the end of the queue.

dequeue(): Removes an element from the front of the queue and returns it.

front(): Returns the front element of the queue without removing it.

isEmpty(): Checks if the queue is empty.

size(): Returns the size of the queue.

printQueue(): Prints all the elements of the queue.

What's Next?

We've now entered the finance section on this platform, where you can enhance your financial literacy.