Skip to content

Instantly share code, notes, and snippets.

@jtompkins
Created November 3, 2017 21:55
Show Gist options
  • Save jtompkins/f26b08dc1cc90e45195b48457ae52bd3 to your computer and use it in GitHub Desktop.
Save jtompkins/f26b08dc1cc90e45195b48457ae52bd3 to your computer and use it in GitHub Desktop.
class LinkedList {
static fromString(str) {
return [...str].reduce((acc, next) => acc.shift(next), new LinkedList())
}
constructor(initial) {
this.head = initial ? new ListNode(initial) : null
}
shift(value) {
const node = new ListNode(value)
node.next = this.head
this.head = node
return this
}
*[Symbol.iterator]() {
let next = this.head
while (next != null) {
yield next
next = next.next
}
}
toString() {
return [...this].reverse().reduce((acc, next) => (acc += next), '')
}
toInt() {
return Number.parseInt(this.toString())
}
add(ll) {
const sum = this.toInt() + ll.toInt()
return LinkedList.fromString(sum.toString())
}
}
class ListNode {
constructor(value, next) {
this.value = value
this.next = next
}
toString() {
return this.value.toString()
}
}
const testLinkedList = (() => {
const left = LinkedList.fromString('123')
const right = LinkedList.fromString('123')
const result = left.add(right)
console.log(result.toInt())
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment