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
head -> [curr->1] -> 2 -> 3 -> null
head -> 1 -> [curr->2] -> 3 -> null
head -> 1 -> 2 -> [curr->3] -> null
head -> 1 -> 2 -> 3 -> [curr->null]
head -> 1 -> 2 -> 3 -> null Length = 3
class Node { constructor(value) { this.value = value; this.next = null; } } class LinkedList { constructor() { this.head = null; } append(value) { const newNode = new Node(value); if (!this.head) { this.head = newNode; return; } let curr = this.head; while (curr.next) { curr = curr.next; } curr.next = newNode; } getLength() { let count = 0; let curr = this.head; while (curr !== null) { count++; curr = curr.next; } return count; } } // Driver code const list = new LinkedList(); list.append(1); list.append(2); list.append(3); console.log("List length:", list.getLength());
while (curr !== null) {count++;curr = curr.next;while (curr !== null) {while (curr !== null) {class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
const head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
let length = 0;
let current = head;
while (current !== null) {
length++;
current = current.next;
}
console.log(length);function getLength(head) {
let length = 0;
let current = head;
while (current.next !== null) {
length++;
current = current.next;
}
return length;
}Pass the test and this pattern moves unknown