class DoublyLinkedList{
constructor(value){
this.head={
value:value,
next:null,
previous:null
}
this.tail=this.head
this.length=1
}
append(value){
const newNode={
value:value,
next:null,
previous:null
};
newNode.previous=this.tail
this.tail.next=newNode;
this.tail=newNode;
this.length++;
return this;
}
prepend(value){
const newNode={
value:value,
next:null,
previous:null
};
this.head.previous=newNode
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;
}
console.log(array)
return array;
}
insert(index,value){
if(index>=this.length){
return this.append(value)
}
if(index===0){
return this.prepend(value)
}
const newNode={
value:value,
next:null,
previous:null
};
const leader=this.traverseIndex(index-1)
const follower=leader.next;
leader.next=newNode;
newNode.previous=leader
newNode.next=follower;
this.length++;
return this.printList
}
traverseIndex(index){
let counter=0;
let currentNode=this.head;
while(counter!=index){
currentNode=currentNode.next;
counter++;
}
return currentNode
}
remove(index){
const leader=this.traverseIndex(index-1);
const unWantedNode=leader.next;
const forwardNode=unWantedNode.next;
leader.next=unWantedNode.next;
forwardNode.previous=leader
this.length--;
return this;
}
reverse(){
if(!this.head.next){
return this.head;
}
let first=this.head;
this.tail=this.head;
let second=first.next;
while (second){
const temp=second.next;
second.next=first;
first=second;
second=temp;
}
this.head.next=null;
this.head=first;
return this;
}
}
const myLinkedList=new DoublyLinkedList(10)
myLinkedList.append(3)
myLinkedList.append(16)
myLinkedList.prepend(4)
myLinkedList.prepend(69)
myLinkedList.remove(1)
myLinkedList.insert(1,34)
myLinkedList.insert(1,45)
myLinkedList.reverse()