Created
May 24, 2024 04:00
-
-
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
This file contains 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 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