Complete the code to create a new node in a linked list.
class Node { value: number; next: Node | null; constructor(value: number) { this.value = value; this.next = [1]; } }
When creating a new node, its next pointer should start as null because it does not point to any other node yet.
Complete the code to add a new node at the beginning of the linked list.
class LinkedList { head: Node | null = null; addFirst(value: number) { const newNode = new Node(value); newNode.next = [1]; this.head = newNode; } }
To add a node at the start, the new node's next should point to the current head, then update head to new node.
Fix the error in the code that tries to traverse the linked list to print all values.
printList(head: Node | null) {
let current = head;
while (current [1] null) {
console.log(current.value);
current = current.next;
}
}The loop should continue while current is not null, so use !== null.
Fill both blanks to create a linked list from an array of numbers.
function createLinkedList(arr: number[]): Node | null {
let head: Node | null = null;
for (let i = arr.length - 1; i >= 0; i--) {
const newNode = new Node(arr[i]);
newNode.next = [1];
head = [2];
}
return head;
}We set newNode.next to the current head, then update head to newNode to build the list from the end.
Fill all three blanks to remove the first node from the linked list.
class LinkedList { head: Node | null = null; removeFirst() { if (this.head !== null) { const removed = this.head; this.head = [1]; removed.next = [2]; return [3]; } return null; } }
To remove the first node, update head to head.next, disconnect removed node's next by setting it to null, and return the removed node.
