Created
March 25, 2023 00:48
-
-
Save fortunee/eca4d30e9c4c76dd1df53f3fa8d87542 to your computer and use it in GitHub Desktop.
Queue
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.size = 0; | |
this.first = null; | |
this.last = null; | |
} | |
enqueue(value) { | |
const newNode = new Node(value); | |
if (!this.first) { | |
this.first = newNode; | |
this.last = this.first; | |
} else { | |
this.last.next = newNode; | |
this.last = newNode; | |
} | |
return ++this.size; | |
} | |
dequeue() { | |
if (!this.first) return; | |
const temp = this.first; | |
if (this.first === this.last) { | |
this.last = null; | |
} | |
this.first = temp.next; | |
this.size--; | |
return temp.value; | |
} | |
} | |
const queue = new Queue(); | |
queue.enqueue(1); | |
queue.enqueue(2); | |
queue.enqueue(4); | |
queue.dequeue(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment