class LinkedList {
constructor(value) {
this.head = {
value: value,
next: null
};
this.tail = this.head;
this.length = 1;
}
append(value) {
const newNode = {
value: value,
next: null
}
this.tail.next = newNode
this.tail = newNode
this.length++
}
prepend(value) {
const newNode = {
value: value,
next: null
}
newNode.next = this.head
this.head = newNode
this.length++
}
printList() {
let array = []
let currentNode = this.head
while (currentNode !== null) {
array.push(currentNode.value)
currentNode = currentNode.next
}
console.log(array)
}
insert(index, value) {
if (index >= this.length) {
this.append(value)
}
if (index === 0) {
this.append(value)
}
const newNode = {
value: value,
next: null
}
const leader = this.traverseToIndex(index-1)
const pointer = leader.next
leader.next = newNode
newNode.next = pointer
this.length++
return this.printList()
}
remove(index) {
const leader = this.traverseToIndex(index-1)
const nodeToBeRemoved = leader.next
leader.next = nodeToBeRemoved.next
this.length--
return this.printList()
}
traverseToIndex(index) {
let count = 0
let currentNode = this.head
while (count !== index) {
count++
currentNode = currentNode.next
}
return currentNode
}
}
let myLinkedList = new LinkedList(10);
console.log(myLinkedList)
myLinkedList.append(5);
myLinkedList.append(16);
myLinkedList.append(20);
myLinkedList.insert(2, 14)
myLinkedList.remove(3)