Mental Model
Add a new item right at the start so it becomes the first thing in the list.
Analogy: Imagine putting a new book on the front of a line of books on a shelf, pushing the others back.
null head -> null
null head -> null
1 -> null head -> 2 -> 3 -> null
1 -> 2 -> 3 -> null head -> 2 -> 3 -> null
head -> 1 -> 2 -> 3 -> null
head -> 1 -> 2 -> 3 -> null
class Node { value: number; next: Node | null; constructor(value: number) { this.value = value; this.next = null; } } class LinkedList { head: Node | null; constructor() { this.head = null; } insertAtBeginning(value: number): void { const newNode = new Node(value); // create new node newNode.next = this.head; // link new node to current head this.head = newNode; // update head to new node } printList(): void { let curr = this.head; let result = ''; while (curr !== null) { result += curr.value + ' -> '; curr = curr.next; } result += 'null'; console.log(result); } } // Driver code const list = new LinkedList(); list.insertAtBeginning(3); list.insertAtBeginning(2); list.insertAtBeginning(1); list.printList();
const newNode = new Node(value); // create new nodenewNode.next = this.head; // link new node to current headthis.head = newNode; // update head to new nodenewNode.next = this.head; // link new node to current head
this.head = newNode; // update head to new node
class Node {
value: number;
next: Node | null = null;
constructor(value: number) { this.value = value; }
}
let head: Node | null = new Node(10);
let newNode = new Node(5);
newNode.next = head;
head = newNode;class Node {
value: number;
next: Node | null = null;
constructor(value: number) { this.value = value; }
}
let head: Node | null = null;
let newNode = new Node(7);
head.next = newNode;
head = newNode;Pass the test and this pattern moves unknown