class Node {
constructor(value) {
this.value = value;
this.prev = null;
this.next = null;
}
}
class DoublyLinkedList {
constructor(value) {
this.head = {
value: value,
prev: null,
next: null
};
this.tail = this.head;
this.length = 1;
}
append(value) {
const newNode = new Node(value);
this.tail.next = newNode;
newNode.prev = this.tail;
this.tail = newNode;
this.length++;
return this;
}
prepend(value) {
const newNode = new Node(value);
newNode.next = this.head;
this.head.prev = newNode;
this.head = newNode;
this.length++;
return this;
}
traverseToIndex(index) {
let counter = 0;
let currentNode = this.head;
while (counter !== index) {
currentNode = currentNode.next;
counter++;
}
return currentNode;
}
insert(index, value) {
if (index === 0) {
return this.prepend(value);
}
if (index >= this.length) {
return this.append(value);
}
let node = this.traverseToIndex(index - 1);
const newNode = new Node(value);
const temp = node.next;
node.next = newNode;
newNode.prev = node;
newNode.next = temp;
temp.prev = newNode;
this.length++;
return this;
}
remove (index) {
let node = null;
if (index === 0) {
node = this.head;
let temp = node.next;
temp.prev = null;
this.head = temp;
this.length--;
return this;
}
node = this.traverseToIndex(index-1);
let nodeToBeRemoved = node.next;
let successor = nodeToBeRemoved.next;
// nodeToBeRemoved.next = null;
node.next = successor;
successor.prev = node;
this.length--;
return this;
}
// print the elements in the linked list
printList() {
const values = [];
let node = this.head;
while (node !== null) {
values.push(node.value);
node = node.next;
}
console.log(values.join(" <=> ") + " length = " + this.length);
}
}
// -----------------------
const myLinkedList = new DoublyLinkedList(10);
myLinkedList.printList();
myLinkedList.append(5);
myLinkedList.printList();
myLinkedList.append(15);
myLinkedList.printList();
myLinkedList.append(20);
myLinkedList.printList();
// -----------------------
myLinkedList.prepend(1);
myLinkedList.printList();
myLinkedList.prepend(0);
myLinkedList.printList();
myLinkedList.insert(2, 12);
myLinkedList.printList();
myLinkedList.insert(3, 13);
myLinkedList.printList();
myLinkedList.insert(0, 21);
myLinkedList.printList();
myLinkedList.insert(200, 25);
myLinkedList.printList();
// myLinkedList.remove(0);
// myLinkedList.printList();
myLinkedList.remove(3);
myLinkedList.printList();