Skip to content

Instantly share code, notes, and snippets.

@another-guy
Last active August 21, 2024 22:44
Show Gist options
  • Save another-guy/98d0843b03991e2744869f11b2ac9439 to your computer and use it in GitHub Desktop.
Save another-guy/98d0843b03991e2744869f11b2ac9439 to your computer and use it in GitHub Desktop.
LeetCode: linked-list-based stack, more performant than default JS's array-based one
function createStack() {
const empty = { next: undefined, value: undefined! };
let top = empty;
function isEmpty() { return top === empty; }
function push(v) { top = { next: top, value: v }; }
function pop() {
if (!top.next) throw new Error('Can not pop from empty');
const { value } = top;
top = top.next;
return value;
}
function peek() { return top.value; }
function clear() { top = empty; }
return { isEmpty, push, pop, peek, clear };
};
// ts
function createStack<T>() {
const empty: Elem<T> = { next: undefined, value: undefined! };
let top: Elem<T> = empty;
function isEmpty(): boolean { return top === empty; }
function push(v: T) { top = { next: top, value: v }; }
function pop(): T {
if (!top.next) throw new Error('Can not pop from empty');
const { value } = top;
top = top.next;
return value;
}
function peek(): T { return top.value; }
function clear(): void { top = empty; }
return { isEmpty, push, pop, peek, clear };
};
interface Elem<T> {
next?: Elem<T>;
value: T;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment