Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Queues

data structure - queue

What are queues?
  1. The queues are First in First out (FIFO) data structures
  2. Its the opposite of stacks
  3. The printer is the best example of a queue
Doubly ended queues
Its a data structure which is both First in First out (FIFO), and Last in Last out (LILO)
Write a code
Let’s implement a queue in Javascript
 // Queue in Javascript
  class Node {
  constructor(data) {
    this.data = data;
    this.next = null;
  }
}

class Queue {
  constructor() {
    this.first = null;
    this.last = null;
    this.length = 0;
  }
  enqueue(data) {
    const newNode = new Node(data);
    if (this.length === 0) {
      this.first = newNode;
      this.last = newNode;
    } else {
      this.last.next = newNode;
      this.last = newNode;
    }
    this.length++;
    return this;
  }
  dequeue() {
    if (!this.first) {
      return null;
    }
    if (this.first === this.last) {
      this.last = null;
    }
    const holdingPointer = this.first;
    this.first = this.first.next;
    this.length--;
    return this;
  }
  //isEmpty;
}

const queueInstance = new Queue();
queueInstance.enqueue('John');
console.log(queueInstance);
queueInstance.enqueue('Stark');
console.log(queueInstance);
queueInstance.dequeue();
console.log(queueInstance);
queueInstance.dequeue();
console.log(queueInstance);

// Output
// Queue {
//   first: Node { data: 'John', next: null },
//   last: Node { data: 'John', next: null },
//   length: 1
// }
// Queue {
//   first: Node { data: 'John', next: Node { data: 'Stark', next: null } },
//   last: Node { data: 'Stark', next: null },
//   length: 2
// }
// Queue {
//   first: Node { data: 'Stark', next: null },
//   last: Node { data: 'Stark', next: null },
//   length: 1
// }
// Queue { first: null, last: null, length: 0 }