function LNode(element) {
this.element = element;
this.next = null;
}
function findPrev(index) {
if (this.head.next && index < this.length) {
let tNode = this.head
while (index--) {
tNode = tNode.next
}
return tNode
}
return null
}
function insert(lNode, index) {
if (index) {
let tNode
if (tNode = this.findPrev(index)) {
lNode.next = tNode.next
tNode.next = lNode
}
} else {
lNode.next = this.head.next
this.head.next = lNode
}
this.length++
}
function remove(index) {
let lNode
if (this.head.next) {
if (index < this.length) {
lNode = this.head
while (index--) {
lNode = lNode.next
}
lNode.next = lNode.next.next
}
}
}
function find(index) {
if (this.head.next && index < this.length) {
let tNode = this.head.next
while (index--) {
tNode = tNode.next
}
return tNode
}
return null
}
export default function LList() {
this.head = new LNode('head');
this.find = find;
this.length = 0;
this.insert = insert;
this.remove = remove;
this.findPrev = findPrev;
}
LList.prototype.toString = function () {
let tNode = this.head
const toStrArr = []
let length = this.length
while (length--) {
tNode = tNode.next
tNode && toStrArr.push(tNode.element)
}
return toStrArr
}
const lList = new LList()
for (let i = 0; i < 10; i++) {
lList.insert(new LNode('data' + i))
}
lList.insert(new LNode('datamy'), 1)
console.log(LList.prototype)
console.log(lList)
console.log(lList.toString())