Skip to content

Instantly share code, notes, and snippets.

@YKalashnikov
Created April 21, 2021 00:08
Show Gist options
  • Save YKalashnikov/1898a12da1677920a21903e52067c39f to your computer and use it in GitHub Desktop.
Save YKalashnikov/1898a12da1677920a21903e52067c39f to your computer and use it in GitHub Desktop.
class LinkedList {
constructor() {
this.head = null
this.tail = null
}
append (data) {
const node = {data, next: null}
if(!this.head) {
this.head = node
}
if(this.tail) {
this.tail.next = node
}
this.tail = node
}
prepend(data) {
const node = {data, next:this.head}
if(!this.tail) {
this.tail = node
}
this.head = node
}
find(data) {
let current = this.head
while(current) {
if(current.data === data) {
return current
}
current = current.next
}
if(!this.head){
return
}
}
remove(data) {
if(!this.head) {
return
}
while(this.head && this.head.data === data) {
this.head = this.head.next
}
let current = this.head
while(current.next) {
if(current.next.data === data) {
current.next = current.next.next
}else {
current = current.next
}
}
if(this.tail.data === data) {
this.tail = current
}
}
toArray() {
const output = []
let current = this.head
while(current) {
output.push(current)
console.log(output)
current = current.next
}
}
}
const list = new LinkedList()
list.append('one')
list.append('two')
list.prepend('1')
list.prepend('2')
list.remove('one')
console.log(list.toArray())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment