Complete the code to declare an array in TypeScript.
const numbers: number[] = [1];The correct syntax to declare an array literal in TypeScript uses square brackets [].
Complete the code to create a simple linked list node class in TypeScript.
class ListNode { value: number; next: ListNode | null; constructor(value: number) { this.value = value; this.next = [1]; } }
In a linked list, the next pointer is null when there is no next node.
Fix the error in the function that adds an element to the end of a linked list.
function appendNode(head: ListNode | null, value: number): ListNode {
const newNode = new ListNode(value);
if (head === null) {
return newNode;
}
let current = head;
while (current.next !== [1]) {
current = current.next;
}
current.next = newNode;
return head;
}The loop should continue until current.next is null, meaning the end of the list.
Fill both blanks to create a function that converts an array to a linked list.
function arrayToLinkedList(arr: number[]): ListNode | null {
if (arr.length === 0) return null;
const head = new ListNode(arr[0]);
let current = head;
for (let i = 1; i [1] arr.length; i++) {
current.next = new ListNode(arr[[2]]);
current = current.next;
}
return head;
}The loop runs while i is less than arr.length, and the current node's next is set to a new node with arr[i].
Fill all three blanks to create a function that converts a linked list back to an array.
function linkedListToArray(head: ListNode | null): number[] {
const result: number[] = [];
let current = [1];
while (current !== [2]) {
result.push(current.[3]);
current = current.next;
}
return result;
}Start from head, loop until current is null, and push current.value to the array.
