Mental Model
Count how many nodes are in the linked list by moving from the start to the end one by one.
Analogy: Like counting people in a line by asking each person to point to the next until no one is left.
head -> 1 -> 2 -> 3 -> null
head -> 1 -> 2 -> 3 -> null
[curr->1] -> 2 -> 3 -> null
1 -> [curr->2] -> 3 -> null
1 -> 2 -> [curr->3] -> null
1 -> 2 -> 3 -> [curr->null]
1 -> 2 -> 3 -> null Length = 3
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; } getLength(): number { let count = 0; let curr = this.head; while (curr !== null) { count++; curr = curr.next; } return count; } append(value: number): void { const newNode = new Node(value); if (this.head === null) { this.head = newNode; return; } let curr = this.head; while (curr.next !== null) { curr = curr.next; } curr.next = newNode; } } // Driver code const list = new LinkedList(); list.append(1); list.append(2); list.append(3); console.log(list.getLength());
let count = 0;
let curr = this.head;while (curr !== null) {count++;curr = curr.next;return count;while (curr !== null) {while (curr !== null) {getLength(head: ListNode | null): number typically return when given the head of a linked list?getLength is designed to count nodes, so it returns the number of nodes in the list.count to start counting nodes in a linked list?count should be initialized to 0.null, head, or undefined is incorrect for counting.class ListNode {
val: number;
next: ListNode | null;
constructor(val: number) {
this.val = val;
this.next = null;
}
}
function getLength(head: ListNode | null): number {
let count = 0;
let current = head;
while (current !== null) {
count++;
current = current.next;
}
return count;
}
const node1 = new ListNode(10);
const node2 = new ListNode(20);
const node3 = new ListNode(30);
node1.next = node2;
node2.next = node3;
console.log(getLength(node1));function getLength(head: ListNode | null): number {
let count = 0;
let current = head;
while (current.next !== null) {
count++;
current = current.next;
}
return count;
}current.next !== null, so it stops before the last node.next is null, it is not counted, so length is one less than actual.val and next, how would you modify the getLength function to return 0 if the list is empty and the correct length otherwise?head is null before counting; if yes, return 0 immediately.head is not null, loop through nodes incrementing count until current is null.Pass the test and this pattern moves unknown