Skip to content

Instantly share code, notes, and snippets.

@gabemeola
Created February 6, 2018 18:54
Show Gist options
  • Save gabemeola/1582cf6457d00af6de2de017067ec564 to your computer and use it in GitHub Desktop.
Save gabemeola/1582cf6457d00af6de2de017067ec564 to your computer and use it in GitHub Desktop.
Queue
/**
* 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