Skip to content

Instantly share code, notes, and snippets.

@kutyel
Last active August 30, 2018 18:32
Show Gist options
  • Save kutyel/7da517fd7862125f6ded9ca29e386678 to your computer and use it in GitHub Desktop.
Save kutyel/7da517fd7862125f6ded9ca29e386678 to your computer and use it in GitHub Desktop.
Simplest Singly Linked List in JavaScript
class LinkedList {
head = null
tail = null
add (value) {
const node = { value, next: null }
if (!this.head) this.head = node
if (this.tail) {
this.tail.next = node
}
this.tail = node
}
remove () {
if (this.head) {
const value = this.head.value
this.head = this.head.next
if (!this.head) this.tail = null
return value
}
}
*values () {
let current = this.head
while (current) {
yield current.value
current = current.next
}
}
}
export const List = (...xs) => ({
add: x => List(x, xs),
remove: () => List(...xs.slice(1)),
values: () => xs
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment