class Node{
constructor(val){
this.value = val;
this.next=null;
this.prev=null;
}
}
class DoubleLinkedList{
constructor(val){
this.head = new Node(val);
this.tail = this.head;
this.length=1;
}
printList(){
const array=[];
let node = this.head;
while(node){
array.push(node.value);
node = node.next;
}
return array;
}
prepend(val){
const newNode = new Node(val);
newNode.next = this.head;
this.head.prev=newNode;
this.head = newNode;
if (this.length === 1){
this.tail.prev = this.head;
}
this.length++;
}
append(val){
const newNode = new Node(val);
newNode.prev = this.tail;
this.tail.next = newNode;
this.tail=newNode;
if (this.length === 1){
this.head.next = this.tail;
}
this.length++;
}
traverseByValue(val){
let node= this.head;
let i=0;
while(node){
if(node.value === val){
return i;
}
node = node.next;
i++;
}
return "Element not present";
}
traverseByIndex(index){
let node= this.head;
let i=0;
while(node){
if(i === index){
return node.value;
}
node = node.next;
i++;
}
return "Index not present";
}
getNodeByIndex(index){
let node = this.head;
let i=0;
while(node){
if (i===index){
return node;
}
i++;
node = node.next;
}
return null;
}
insert(index,val){
if (index===0){
this.prepend(val);
return;
}
if (index===this.length){
this.append(val);
return;
}
let node = this.getNodeByIndex(index);
let newNode = new Node(val);
if (node){
let prevNode = node.prev;
prevNode.next = newNode;
newNode.next = node;
}
this.length++;
}
remove(index){
let node = this.getNodeByIndex(index);
let prevNode = node.prev;
let nextNode = node.next;
this.length--;
if(!prevNode){
this.head = node.next;
this.head.prev=null;
return;
}
if (!nextNode){
this.tail = node.prev;
this.tail.next = null;
return;
}
prevNode.next = nextNode;
nextNode.prev = prevNode;
}
}
const myDLL = new DoubleLinkedList(2);
//console.log(myDLL);
myDLL.append(5);
//myDLL.append(10);
myDLL.prepend(1);
console.log(myDLL.printList());
//console.log(myDLL.traverseByValue(5));
//console.log(myDLL.traverseByIndex(0));
myDLL.insert(3,-1);
console.log(myDLL.printList());
myDLL.remove(0);
console.log(myDLL.printList());