Skip to content

Instantly share code, notes, and snippets.

@0livare
Last active May 17, 2019 13:01
Show Gist options
  • Save 0livare/8a628c6ab27f85270666d7a2c21c0f55 to your computer and use it in GitHub Desktop.
Save 0livare/8a628c6ab27f85270666d7a2c21c0f55 to your computer and use it in GitHub Desktop.
// Interview question:
//
// What is a linked list? Implement one in JavaScript without
// using an array. (I did this in about ten minutes)
//
// What is the time complexity of add()? How can you make it O(1)?
class Node {
constructor(value) {
this.value = value
}
}
class LinkedList {
add(node) {
if (!this.head) {
this.head = node
return
}
let tail = this.head
while(tail.next) tail = tail.next
tail.next = node
}
remove(node) {
if (!node) return
if (node === this.head) {
this.head = this.head.next
}
let n = this.head
while(n.next) {
if (n.next === node) {
n.next = node.next
return
}
n = n.next
}
}
}
let list = new LinkedList()
let one = new Node("one")
let two = new Node("two")
let three = new Node("three")
list.add(one)
list.add(two)
list.add(three)
list.remove(two)
console.log(list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment