// 10---> 5 ---> 16
class Node{
constructor(value){
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor(value){
this.head = {
value: value,
next: null
}
this.tail = this.head;
this.length=1;
}
// 1--> 10 --> 5 ---> 16
prepend(value){
let tempNode= this.head ;
const newNode = new Node(value);
newNode.next = this.head;
this.head = newNode;
// this.head.next = tempNode;
this.length++;
return this;
}
append(value){
const newNode = new Node(value);
this.tail.next = newNode;
this.tail = 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){ //o(n)
if(index >= this.length){
return this.append(value);
}
const newNode = new Node(value);
//0,1,10
const leader = this.traverseToIndex(index-1);
const holdingPointer = leader.next; //5
leader.next = newNode; //10--99
newNode.next = holdingPointer;//99--5
this.length++;
return this.printList();
}
//0--1---10--99--5--16
//0--1---10--5--16
remove(index){
const leader = this.traverseToIndex(index-1);//gives 10
const unwantedNode = leader.next; //gives 99
//console.log(leader);
leader.next = unwantedNode.next;
this.length--;
return this.printList();
}
traverseToIndex(index){
let counter = 0;
let currentNode = this.head;
while(counter!== index){
currentNode = currentNode.next;
counter++;
}
return currentNode;
}
}
const myLinkedList = new LinkedList(10);
myLinkedList.append(5);
myLinkedList.append(16);
myLinkedList.prepend(1);
myLinkedList.prepend(0);
myLinkedList.insert(3,99);
myLinkedList.remove(3);
console.log(myLinkedList.printList());