Queue

Run Settings
LanguageJavaScript
Language Version
Run Command
class Node { constructor(value) { this.value = value; this.next = null; } } class Queue { constructor() { this.first = null; this.last = null; this.length = 0; } peek() { return this.first; } enqueue(value) { let node = new Node(value); // if the queue is empty if (this.length === 0) { this.first = node; this.last = node; this.length++; return this; } // if the queue is not empty this.last.next = node; this.last = node; this.length++; return this; } dequeue() { // if the queue is empty if (this.length === 0) { return null; } // if the queue has only 1 element if (this.length === 1) { let val = this.first; this.first = null; this.last = null; this.length--; return val.value; } let val = this.first; this.first = this.first.next; this.length--; return val.value; } isEmpty() { return (this.length === 0); } // print the elements in the queue printList() { const values = []; let val = this.first; while (val !== null) { values.push(val.value); val = val.next; } console.log(values.join(",")); } } const myQueue = new Queue(); // console.log(myQueue.isEmpty()); // console.log(myQueue.dequeue()); myQueue.enqueue(10); myQueue.enqueue(20); myQueue.enqueue(30); myQueue.enqueue(40); myQueue.printList(); console.log(myQueue.dequeue()); myQueue.printList(); // console.log(myQueue.peek()); // myQueue.printList(); // console.log(myQueue.dequeue()); // myQueue.printList(); // console.log(myQueue.dequeue()); // myQueue.printList(); // console.log(myQueue.isEmpty()); // console.log(myQueue.length); // console.log(myQueue);
Editor Settings
Theme
Key bindings
Full width
Lines