class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor(value) {
this.head = new Node(value);
this.tail = this.head;
this.length = 1;
}
append(value){
const newNode = new Node(value);
this.tail.next = newNode;
this.tail = newNode;
this.length++;
return this;
}
prepend(value){
const newNode = new Node(value);
this.newNode.next = this.head;
this.head = newNode;
this.length++;
return this;
}
printList(){
const array = []
let currentNode = this.head;
while(currentNode !== null){
array.push(currentNode.value);
currentNode = currentNode.next;
}
return array;
}
insert(index, value){
if (index >= this.length) {
this.append(value);
return this.printList();
}
if (index === 0) {
this.prepend(value);
return this.printList();
}
const preNode = this._traverseToIndex(index - 1);
const postNode = currentNode.next;
const newNode = new Node(value);
preNode.next = newNode;
newNode.next = postNode;
this.lenght++;
return this.printList();
}
remove(index){
const preNode = this._traverseToIndex(index - 1);
const postNode = preNode.next.next;
preNode.next = postNode;
this.length--;
return this.printList();
}
_traverseToIndex(index){
let currentNode = this.head;
let count = 0;
while(count !== index) {
currentNode = currentNode.next;
count++;
}
return currentNode;
}
}
const myLinkedList = new LinkedList(1);
myLinkedList.append(2);
myLinkedList.append(3);
myLinkedList.append(4);
myLinkedList.append(5);
myLinkedList.insert(2, 100);
myLinkedList.insert(4, 400);
console.log('myLinkedList:', myLinkedList.printList());