Last active
August 21, 2024 22:44
-
-
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
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
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