Complete the code to create a Node class with a constructor that sets the value and next pointer.
class Node { constructor(value) { this.value = value; this.next = [1]; } }
The next pointer should be initialized to null because the new node does not point to any other node yet.
Complete the code to initialize the head of the linked list to null in the constructor.
class LinkedList { constructor() { this.head = [1]; } }
The head should be initialized to null to indicate the list is empty at the start.
Fix the error in the add method to correctly add a new node at the end of the list.
add(value) {
const newNode = new Node(value);
if (this.head === null) {
this.head = newNode;
} else {
let current = this.head;
while (current.next [1] null) {
current = current.next;
}
current.next = newNode;
}
}The loop should continue while current.next is not null to reach the last node.
Fill both blanks to complete the printList method that prints all node values.
printList() {
let current = this.head;
while (current [1] null) {
console.log(current.[2]);
current = current.next;
}
}The loop continues while current is not null, and we print the value of the current node.
Fill all three blanks to complete the remove method that deletes the first node with the given value.
remove(value) {
if (this.head === null) return;
if (this.head.[1] === value) {
this.head = this.head.[2];
return;
}
let current = this.head;
while (current.next !== null && current.next.[3] !== value) {
current = current.next;
}
if (current.next !== null) {
current.next = current.next.next;
}
}We check the value of the head node, then update head to head.next if it matches. Then we traverse to find the node before the one to remove by checking current.next.value.
