Created
April 4, 2020 04:56
-
-
Save JustAyush/0d4b1a686dfd8ba05877373c2f795fb6 to your computer and use it in GitHub Desktop.
Queue Implementation in JavaScript
This file contains hidden or 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.head = null; | |
this.tail = null; | |
} | |
enqueue(value) { | |
if(this.head == null) { | |
this.head = this.tail = new Node(value); | |
} else { | |
let node = this.head; | |
while(node.next != null) { | |
node = node.next; | |
} | |
node.next = new Node(value); | |
this.tail = node.next; | |
} | |
} | |
dequeue() { | |
let nodeToRemove = this.head; | |
if(this.head == null) { | |
return nodeToRemove; | |
} else { | |
this.head = this.head.next; | |
} | |
if(this.head == null) { | |
this.head = this.tail = null; | |
} | |
return nodeToRemove; | |
} | |
print() { | |
console.log("Head", this.head); | |
console.log("Tail", this.tail); | |
} | |
} | |
let q = new Queue(); | |
q.enqueue(1); | |
q.enqueue(2); | |
q.enqueue(3); | |
q.dequeue(); | |
q.dequeue(); | |
q.dequeue(); | |
q.print(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment