Skip to content

Instantly share code, notes, and snippets.

@kleinron
Last active November 14, 2021 15:38
Show Gist options
  • Save kleinron/9d9fe8dece1f038f376db4206438b9c5 to your computer and use it in GitHub Desktop.
Save kleinron/9d9fe8dece1f038f376db4206438b9c5 to your computer and use it in GitHub Desktop.
minimal implementation for a queue backed by a singly linked list
class LinkedQueue {
constructor() {
this._newest = null;
this._oldest = null;
this._size = 0;
}
enqueue(item) {
if (this._size === 0) {
this._newest = {value: item, next: null};
this._oldest = this._newest;
} else {
const temp = {value: item, next: null};
this._newest.next = temp;
this._newest = temp;
}
this._size++;
}
dequeue() {
const oldest = this._oldest;
const result = oldest.value;
oldest.value = null;
this._oldest = oldest.next;
this._size--;
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment