class LinkedList{
constructor(value){
this.head = {
data: value,
next: null,
prev: null
}
this.tail = this.head
this.length = 1
}
append(val){
const node = {
data: val,
next: null,
prev: this.tail
}
this.tail.next = node
this.tail = node
this.length++
return this
}
prepend(val){
const node = {
data: val,
next: null,
prev: null
}
node.next = this.head
this.head.prev = node
this.head = node
this.length++
return this
}
insert(value, pos){
let i = 1
let target = this.head
while (i!=pos){
target = target.next
i++
}
const node = {
data: value,
next: null,
prev: null
}
node.next = target.next
let nextNode = target.next
nextNode.prev = node
node.prev = target
target.next = node
this.length++
}
remove(i){
let counter = 1
let currentNode = this.head
while (counter!= i){
currentNode = currentNode.next
counter++
}
let temp = currentNode.next
currentNode.next = temp.next
let nextNode = temp.next
nextNode.prev = currentNode
temp.next = null
temp.prev = null
this.length--
}
printNodes(){
const nodeArray = []
let currentNode = this.head;
while (currentNode){
nodeArray.push(currentNode.data.toString())
currentNode = currentNode.next
}
console.log(nodeArray.join("-->"))
}
}
const lili = new LinkedList(5)
lili.append(12)
lili.append(18)
lili.append(15)
lili.insert(14,2)
lili.printNodes()
lili.remove(2)
console.log(lili)
I made this incomplete implementation of a doubly LinkedList in Javascript. The 2nd node's prev property and the 2nd to last node's next property are both showing [Circular]
instead of [Object]
. Could someone explain what Circular is and why this is happening? Thanks.