Linked Structures
Build a Singly Linked List
Construct a singly linked list by allocating one node per value and
chaining next references. Establishes the node + head + tail model used
by every later linked-list lesson.
Algorithm
Canonical input [10, 20, 30, 40] builds the chain
head -> 10 -> 20 -> 30 -> 40 -> null with one node appended per step.
Basic Implementation
basic.ts
class ListNode {
value: number;
next: ListNode | null;
constructor(value: number) {
this.value = value;
this.next = null;
}
}
const values: number[] = [10, 20, 30, 40];
let head: ListNode | null = null;
let tail: ListNode | null = null;
for (const v of values) {
const node: ListNode = new ListNode(v);
if (head === null) {
head = node;
} else {
tail!.next = node;
}
tail = node;
}
Complexity
- Time: O(n) with a tail pointer
- Space: O(n) for the chain
Implementation notes
- TypeScript: a small
class ListNodewith explicit field types is the idiomatic Node. TheListNode | nullunion typeshead,tail, andnexthonestly. - The replay never shows runtime references; nodes are labelled
node(<value>)and the chain view is rendered as10 -> 20 -> ... -> null.
node chain
Each `ListNode` carries a `value: number` and a `next: ListNode | null` reference.