Last active
July 10, 2021 09:58
-
-
Save darshna09/9533cb4a84a5bf22368fd6319409dfb0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node { | |
constructor(value) { | |
this.value = value; | |
this.next = null; | |
} | |
} | |
class Queue { | |
constructor() { | |
this.first = null; | |
this.last = null; | |
this.length = 0; | |
} | |
// Peek the first element in line | |
peek() { | |
this.length ? console.log(`First in Line = ${this.first.value}`) : console.log('Queue is empty'); | |
return this.length; | |
} | |
// Print the elements in the queue. | |
printList() { | |
let list = []; | |
let currentNode = this.first; | |
while(currentNode !== null) { | |
list.push(currentNode.value); | |
currentNode = currentNode.next; | |
} | |
console.log(list.join(' --> ')); | |
return this.length; | |
} | |
// Add element at the end of the queue. | |
enqueue(value) { | |
let newNode = new Node(value); | |
if (this.length) { | |
this.last.next = newNode; | |
this.last = newNode; | |
} else { | |
this.first = newNode; | |
this.last = newNode; | |
} | |
this.length++; | |
return this.printList(); | |
} | |
// Remove the fist element in the queue. | |
dequeue() { | |
if (this.length) { | |
const tempNode = this.first; | |
this.first = this.first.next; | |
console.log(`Dequeued ${tempNode.value}`); | |
this.length--; | |
} else { | |
this.last = null; | |
console.log('Queue is empty'); | |
} | |
return this.length; | |
} | |
} | |
const myQueue = new Queue(); | |
myQueue.peek(); // Queue is empty | |
myQueue.enqueue('Rachel'); // Rachel | |
myQueue.enqueue('Ross'); // Rachel --> Ross | |
myQueue.enqueue('Monica'); // Rachel --> Ross --> Monica | |
myQueue.enqueue('Joey'); // Rachel --> Ross --> Monica --> Joey | |
myQueue.peek(); // First in Line = Rachel | |
myQueue.dequeue(); // Dequeued Rachel | |
myQueue.dequeue(); // Dequeued Ross | |
myQueue.dequeue(); // Dequeued Monica | |
myQueue.dequeue(); // Dequeued Joey | |
myQueue.dequeue(); // Queue is empty |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment