Last active
February 26, 2020 21:41
-
-
Save Giagnus64/a37527a4bed9fc58eeff08e8a9b3d8f6 to your computer and use it in GitHub Desktop.
Basic Queue Structure for BFS Tree
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 QueueNode { | |
| constructor(value) { | |
| this.value = value; | |
| this.next = null; | |
| } | |
| } | |
| class Queue { | |
| constructor() { | |
| this.first = null; | |
| this.last = null; | |
| this.size = 0; | |
| } | |
| //newnode goes to back of the line/end of the queue | |
| enqueue(value) { | |
| const newNode = new QueueNode(value); | |
| //if queue is empty | |
| if (this.size === 0) { | |
| this.first = newNode; | |
| this.last = newNode; | |
| // add current first pointer to new first(new node), and make new node new first | |
| } else { | |
| this.last.next = newNode; | |
| this.last = newNode; | |
| } | |
| //add 1 to size | |
| this.size++; | |
| return this; | |
| } | |
| // dequeue nodes off the front of the line | |
| dequeue() { | |
| //if queue is empty return false | |
| if (this.size === 0) return false; | |
| //get dequeuedNode | |
| const dequeuedNode = this.first; | |
| //get new first (could be NULL if stack is length 1) | |
| const newFirst = this.first.next; | |
| //if newFirst is null, reassign last to newFirst(null) | |
| if (!newFirst) { | |
| this.last = newFirst; | |
| } | |
| //assign new first | |
| this.first = newFirst; | |
| //remove refernce to list | |
| dequeuedNode.next = null; | |
| //remove 1 from size | |
| this.size--; | |
| //return dequeuednode | |
| return dequeuedNode; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment