Queues
What are queues?
- The queues are First in First out (FIFO) data structures
- Its the opposite of stacks
- 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 }