class Node {
constructor(value = null, next = null) {
this.value = value;
this.next = next;
}
}
class LinkedList {
constructor(value) {
this.head = new Node(value);
this.tail = this.head;
this.length = 1;
}
append(value) {
const newNode = new Node(value);
this.tail.next = newNode;
this.tail = newNode;
this.length++;
return this;
}
prepend(value) {
const newNode = new Node(value, this.head);
this.head = newNode;
this.length++;
return this;
}
insert(index, value) {
if(index === 0) {
return this.prepend(value);
}
if(index > this.length) {
return this.append(value);
}
const newNode = new Node(value);
let currentNode = this.head;
let i = 1; // one step ahead of current Node
while(currentNode !== null) {
if(i === index) {
newNode.next = currentNode.next;
currentNode.next = newNode;
this.length++;
}
currentNode = currentNode.next;
i++;
}
}
toArray() {
const array = [];
let currentNode = this.head;
while(currentNode !== null) {
array.push(currentNode.value);
currentNode = currentNode.next;
}
return array;
}
remove(index) {
if(index > this.length - 1) {
return this;
}
if(index === 0) {
this.head = this.head.next;
this.length--;
return this;
}
let i = 0;
let preIndex = index-1;
let currentNode = this.head;
while(currentNode !== null) {
if(i === preIndex) {
currentNode.next = currentNode.next.next;
this.length--;
}
currentNode = currentNode.next;
i++;
}
}
reverse() {
let reversedList = null;
let currentNode = this.head;
while(currentNode !== null) {
const newNode = new Node(currentNode.value, reversedList);
if(reversedList === null) {
this.tail = newNode;
}
reversedList = newNode;
currentNode = currentNode.next;
}
this.head = reversedList;
return this;
}
}
const myList = new LinkedList(1);
myList.append(2);
myList.append(3);
myList.prepend(0);
// myList.prepend(42);
// myList.insert(2, 777);
// myList.remove(2);
console.log(myList);
// 0 1 2 3
console.log(myList.toArray());
myList.reverse();
console.log(myList);
// 3 2 1 0
console.log(myList.toArray());