How to implement a Queue

// Queue class
class Queue {
  constructor() {
    this.items = [];
  }

  // Method to enqueue an element into the queue
  enqueue(element) {
    this.items.push(element);
  }

  // Method to dequeue an element from the queue
  dequeue() {
    if (this.items.length === 0) {
      return 'Underflow';
    }
    return this.items.shift();
  }

  // Method to display the queue
  display() {
    console.log(this.items);
  }
}

// Example usage
const queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.display();

 

Post your Answer