Created
March 20, 2022 11:42
-
-
Save mustafadalga/93d390c6923d850ac877867523dc896c to your computer and use it in GitHub Desktop.
Queue Data Structure Example
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.size = 0; | |
} | |
enqueue(value) { | |
const newNode = new Node(value); | |
if (this.first) { | |
this.last.next = newNode; | |
this.last = newNode; | |
} else { | |
this.first = newNode; | |
this.last = newNode; | |
} | |
this.size++; | |
return this.size; | |
} | |
dequeue() { | |
if (!this.size) return null; | |
const removedNode = this.first; | |
if (this.first == this.last) { | |
this.last = null; | |
} | |
this.first = removedNode.next; | |
this.size--; | |
return removedNode.value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment