Complete the code to create a new node with given value in a doubly linked list.
class Node { constructor(value) { this.value = value; this.prev = null; this.next = [1]; } }
The next pointer of a new node should be initialized to null because it does not point to any node yet.
Complete the code to initialize the head of the doubly linked list with the first node.
class DoublyLinkedList { constructor() { this.head = [1]; this.tail = null; } }
The list is empty at creation, so head should be null.
Fix the error in the method that adds a new node at the end of the doubly linked list.
addToEnd(value) {
const newNode = new Node(value);
if (this.tail === null) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
newNode.prev = [1];
this.tail = newNode;
}
}The new node's prev should point to the current tail before updating the tail.
Fill both blanks to complete the method that adds a new node at the beginning of the doubly linked list.
addToStart(value) {
const newNode = new Node(value);
if (this.head === null) {
this.head = newNode;
this.tail = newNode;
} else {
newNode.next = [1];
[2].prev = newNode;
this.head = newNode;
}
}The new node's next points to the current head, and the current head's prev points back to the new node.
Fill all three blanks to complete the method that prints all values from head to tail in the doubly linked list.
printList() {
let current = this.head;
while (current !== [1]) {
console.log(current.[2]);
current = current.[3];
}
}The loop runs until current is null, printing the value of each node and moving to the next node.
