/*
What is the linked lists
[5] [10] [2]
head tail => null
*/
class DoublyLinkedList{
constructor(value){
this.head = {
value : value,
next: null,
prev: null
}
this.tail = this.head;
this.length = 1;
}
append(value)
{
//code here
const newNode = {
value :value ,
next : null,
prev: null
};
newNode.prev = this.tail;
this.tail.next = newNode;
this.tail = newNode;
this.length++;
return this;
}
prepend(value){
const newNode = {
value :value ,
next : null,
prev: null
};
newNode.next = this.head;
this.head.prev = newNode;
this.head = newNode;
this.length++;
return this;
}
insert(index, value){
//check my parameter
if(index >= this.length)
{
return this.append(value);
}
const newNode ={
value : value,
next : null,
prev: null
};
const leader = this.traverseToIndex(index-1);
const follower = leader.next;
leader.next = newNode;
newNode.next = follower;
newNode.prev = leader;
follower.prev = newNode;
this.length++;
console.log(this);
return this.printList();
}
traverseToIndex(index)
{
//check params
let counter= 0 ;
let currentNode = this.head;
while(counter !== index)
{
currentNode = currentNode.next;
counter++;
}
return currentNode;
}
printList(){
const array = [];
let currentNode = this.head;
while(currentNode !== null )
{
array.push(currentNode.value);
currentNode = currentNode.next;
}
return array;
}
remove(index){
//check params
const leader = this.traverseToIndex(index-1);
const unWantedNode = leader.next;
leader.next = unWantedNode.next;
this.length--;
return this.printList();
}
}
const myDoublyLinkedList = new DoublyLinkedList(10);
myDoublyLinkedList.append(5);
myDoublyLinkedList.append(16);
myDoublyLinkedList.prepend(1);
myDoublyLinkedList.insert(3,44);
//myLinkedList.remove(2);
//console.log(myDoublyLinkedList);
console.log(myDoublyLinkedList.printList());