Skip to content

Instantly share code, notes, and snippets.

@another-guy
Created May 24, 2024 04:00
Show Gist options
  • Save another-guy/ebaaa8bea039aef32b7f0227ba1676ca to your computer and use it in GitHub Desktop.
Save another-guy/ebaaa8bea039aef32b7f0227ba1676ca to your computer and use it in GitHub Desktop.
LeetCode: linked-list-based queue, more performant than default JS's array-based one
function createQueue() {
let head = undefined;
let tail = head;
function isEmpty() { return head === undefined; }
function push(value) {
const newElement = { next: undefined, value };
if (!tail) {
head = newElement;
tail = newElement;
} else {
tail.next = newElement;
tail = newElement;
}
}
function pop() {
const { value } = head;
head = head.next;
if (!head) tail = undefined;
return value;
}
function peek() { return head.value; }
return { isEmpty, push, pop, peek };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment