class Node {
constructor(value){
this.value = value;
this.prev = null;
this.next = null;
}
}
class DoublyLinkedList {
constructor(value){
this.head = new Node(value);
this.tail = this.head;
this.length = 0;
}
printList(){
let outputArr = [];
let currPointer = this.head;
while(currPointer != null){
outputArr.push(currPointer.value);
currPointer = currPointer.next;
}
console.log(outputArr.join('-->'));
}
prepend(value){
let newNode = new Node(value);
newNode.next = this.head;
this.head.prev = newNode;
this.head = newNode;
this.length++;
return this;
}
append(value){
let newNode = new Node(value);
newNode.prev = this.tail;
this.tail.next = newNode;
this.tail = newNode;
this.length++;
return this;
}
traverseToIndex(index){
let idx = 0;
let currPointer = this.head;
while(currPointer != null && idx!=index){
currPointer = currPointer.next;
idx++;
}
return currPointer;
}
insert(index, value){
if(index == 0){
this.prepend(value);
return this;
}
if(index > this.length){
this.append(value);
return this;
}
let currPointer = this.traverseToIndex(index-1);
let newNode = new Node(value);
newNode.next = currPointer.next;
newNode.next.prev = newNode;
newNode.prev = currPointer;
currPointer.next = newNode;
this.length++;
return this;
}
remove(index){
if(index < this.length){
let currPointer = this.traverseToIndex(index-1);
let unwantedNode = currPointer.next;
unwantedNode.next.prev = currPointer;
currPointer.next = unwantedNode.next;
this.length--;
return this;
}
else if(index == this.length){
let lastNodeNow = this.tail.prev;
lastNodeNow.next = null;
this.tail = lastNodeNow;
this.length--;
return this;
}
}
}
const myLinkedList = new DoublyLinkedList(10);
myLinkedList.prepend(15);
myLinkedList.append(8);
myLinkedList.insert(1,5);
myLinkedList.insert(0,9);
myLinkedList.insert(1,12);
myLinkedList.insert(100,88);
myLinkedList.printList();
myLinkedList.remove(6);
myLinkedList.remove(5);
myLinkedList.printList();
console.log("\n\n\n")
console.log(myLinkedList.head);
console.log(myLinkedList.tail);