class Node {
constructor(value){
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor(value){
this.head = new Node(value);
this.tail = this.head;
this.length = 1;
}
printList(){
let outputArr = [];
let currPointer = this.head;
while(currPointer.next != null){
outputArr.push(currPointer.value);
currPointer = currPointer.next;
}
outputArr.push(currPointer.value);
console.log(outputArr.join('-->'));
}
append(value){
let newNode = new Node(value);
this.tail.next = newNode;
this.tail = newNode;
this.length++;
return this;
}
prepend(value){
let newNode = new Node(value);
newNode.next = this.head;
this.head = newNode;
this.length++;
return this;
}
insert(index, value){
if(index == 0){
this.prepend(value);
return this;
}
if(index >= this.length){
this.append(value);
return this;
}
let newNode = new Node(value);
let currPointer = this.head;
let idx = 0;
while(currPointer.next != null){
if(idx+1 == index){
newNode.next = currPointer.next;
currPointer.next = newNode;
return this;
}
currPointer = currPointer.next;
idx++;
}
this.length++;
return this;
}
remove(index){
if(index >= this.length){
return "Cannot remove"
}
if(index == 0){
let tempHead = this.head.next;
this.head = tempHead;
this.length--;
return this;
}
let currPointer = this.head;
let idx = 0;
while(currPointer != null && idx != index-1){
currPointer = currPointer.next;
idx++;
}
if(currPointer.next != null){
let tempHead = currPointer.next.next;
currPointer.next = tempHead;
}
this.length--;
return this;
}
reverse(){
if(!this.head.next){
return this;
}
let first = this.head;
this.tail = first;
let second = this.head.next;
while(second){
let temp = second.next;
second.next = first;
first = second;
second = temp;
}
this.head.next = null;
this.head = first;
return this;
}
}
const myLinkedList = new LinkedList(10);
myLinkedList.append(5);
myLinkedList.append(3);
myLinkedList.append(16);
myLinkedList.prepend(1);
myLinkedList.printList();
myLinkedList.insert(5, 11);
myLinkedList.printList();
console.log("****************************")
myLinkedList.remove(5);
myLinkedList.printList();
let tempLinkedList = myLinkedList.reverse();
tempLinkedList.printList();