class Node {
constructor(value) {
this.value = value;
this.next = null;
this.prev = null;
}
}
class DoublyLinkedList {
constructor(value) {
this.head = {
value: value,
next : null,
prev: null
};
this.tail = this.head;
this.length = 1;
}
printList() {
console.log(this);
const list = [];
let currentNode = this.head;
while (currentNode !== null) {
list.push(currentNode.value);
currentNode = currentNode.next;
}
console.log(list);
}
append(value) {
const newNode = new Node(value);
if (this.length <= 1) {
newNode.prev = this.head;
this.head.next = newNode;
this.tail = newNode;
this.length++;
// console.log(this);
return this;
}
const currentTail = this.tail;
newNode.prev = currentTail;
this.tail.next = newNode;
this.tail = newNode;
this.length++;
return this;
}
prepend(value) {
const newNode = new Node(value);
const currentHead = this.head;
newNode.next = currentHead;
this.head = newNode;
this.length++;
return this;
}
}
const doublyLinkedList = new DoublyLinkedList(10);
doublyLinkedList.printList();
doublyLinkedList.append(5);
doublyLinkedList.append(42);
doublyLinkedList.append(782);
doublyLinkedList.append(300);
doublyLinkedList.prepend(300);
doublyLinkedList.printList();