Understanding Queue Data Structure in JavaScript ??

Understanding Queue Data Structure in JavaScript ??

A queue is a linear data structure that follows the FIFO (First-In, First-Out) principle. This means that the first element added to the queue is the first one to be removed, similar to how people line up in a queue at a ticket counter.

Applications of Queues

  • Task scheduling: In operating systems, tasks are often scheduled and processed in a queue.
  • Print queues: When multiple users send documents to a printer, they are processed in the order they were submitted.
  • Message Queues: In distributed systems, message queues ensure that messages are processed in the order they are sent.

Queue Operations

There are several key operations associated with queues:

  • Enqueue: Adds an element to the back of the queue.
  • Dequeue: Removes and returns the front element of the queue.
  • Peek: Returns the front element without removing it.
  • Is Empty: Checks if the queue has no elements.
  • Size: Returns the number of elements currently in the queue.

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

  enqueue(element) {
    this.items.push(element);
  }

  dequeue() {
    if (this.isEmpty()) {
      return null;
    }
    return this.items.shift();
  }

  isEmpty() {
    return this.items.length == 0;
  }

  peek() {
    if (this.isEmpty()) {
      return 'No elements in Queue';
    }
    return this.items[0];
  }

  size() {
    return this.items.length;
  }

  printQueue() {
    console.log(this.items.toString());
  }
}

const queue = new Queue();

console.log(queue.isEmpty());
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
console.log(queue.size());
queue.printQueue();
queue.dequeue();
queue.printQueue();
queue.dequeue();
queue.printQueue();        

要查看或添加评论,请登录

Harshit Pandey的更多文章

社区洞察

其他会员也浏览了