Created
February 6, 2018 18:54
-
-
Save gabemeola/1582cf6457d00af6de2de017067ec564 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
/** | |
* Simple Que using linked lists. | |
* Pushed value can be anything. | |
*/ | |
class Queue { | |
constructor() { | |
this.first = null; | |
this.last = null; | |
this.length = 0; | |
} | |
push(value) { | |
const node = { | |
value, | |
next: null, | |
}; | |
const prevLast = this.last; | |
if (this.last !== null) { | |
prevLast.next = node; | |
} | |
this.last = node; | |
if (this.first === null) { | |
this.first = node; | |
} | |
this.length += 1; | |
} | |
shift() { | |
if (this.length === 0) return null; | |
const shiftedFirst = this.first; | |
this.first = shiftedFirst.next; | |
this.length -= 1; | |
return shiftedFirst.value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment