Created
December 25, 2019 05:38
-
-
Save dashsaurabh/014cd2583526802790e314ff87a793b6 to your computer and use it in GitHub Desktop.
Queue Implementation in Javascript
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(val) { | |
this.val = val; | |
this.next = null | |
} | |
} | |
class Queue { | |
constructor(){ | |
this.first = null; | |
this.last = null; | |
this.size = 0 | |
} | |
enqueue(val){ | |
let newNode = new Node(val); | |
if (this.size === 0){ | |
this.first = newNode; | |
this.last = newNode; | |
}else{ | |
this.last.next = newNode; | |
this.last = newNode; | |
} | |
this.size++; | |
} | |
dequeue(){ | |
if (this.size === 0) return null; | |
let node = this.first; | |
if (this.size === 1){ | |
this.first = null; | |
this.last = null | |
}else{ | |
this.first = this.first.next; | |
} | |
this.size-- | |
return node; | |
} | |
} | |
let queue = new Queue(); | |
queue.enqueue(3); | |
queue.enqueue(4); | |
queue.enqueue(5); | |
queue.dequeue(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment