Mental Model
A node holds data and points to the next node, linking pieces like train cars.
Analogy: Imagine a train where each car carries cargo and hooks to the next car, forming a chain.
Node1[data|next] -> Node2[data|next] -> Node3[data|null]
Node1[data|next] -> Node2[data|next] -> Node3[data|null]
[10|null]
[10|null] [20|null]
[10|->] -> [20|null]
[10|->] -> [20|null] [30|null]
[10|->] -> [20|->] -> [30|null]
[10|->] -> [20|->] -> [30|null]
class Node { value: number; next: Node | null; constructor(value: number) { this.value = value; this.next = null; } } function buildLinkedList(values: number[]): Node | null { if (values.length === 0) return null; const head = new Node(values[0]); let current = head; for (let i = 1; i < values.length; i++) { current.next = new Node(values[i]); current = current.next; } return head; } function printList(head: Node | null): void { let current = head; let output = ''; while (current !== null) { output += current.value + ' -> '; current = current.next; } output += 'null'; console.log(output); } const values = [10, 20, 30]; const linkedList = buildLinkedList(values); printList(linkedList);
const head = new Node(values[0]);current.next = new Node(values[i]);current = current.next;while (current !== null) {output += current.value + ' -> ';current = current.next;if (values.length === 0) return null;
const head = new Node(values[0]);next pointer in a singly linked list node represent?next in singly linked listnext pointer is used to link the current node to the following node in the list.prev which points backward, next always points forward to the next node.next pointer = next node [OK]data property and a next pointer?next pointer should allow null to represent the end of the list, so its type must be Node | null.data and sets next to null initially.class Node {
data: number;
next: Node | null;
constructor(data: number) {
this.data = data;
this.next = null;
}
}
const head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
let current = head;
const result: number[] = [];
while (current !== null) {
result.push(current.data);
current = current.next;
}
console.log(result);next pointers link 10 -> 20 -> 30 -> null.class Node {
data: number;
next: Node;
constructor(data: number) {
this.data = data;
this.next = null;
}
}next property is typed as Node but assigned null, which is invalid.Node | null so it can hold either a node or null.prev and next pointers must allow null to represent ends of the list.prev and next to null initially.Pass the test and this pattern moves unknown