Mental Model
Go through each item in the list one by one from start to end and show its value.
Analogy: Like reading a line of people holding hands, you look at each person in order from the first to the last.
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
1 -> 2 -> 3 -> null
class Node { constructor(value) { this.value = value; this.next = null; } } class LinkedList { constructor() { this.head = null; } // Add nodes for testing 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; } // Traverse and print the list printList() { let curr = this.head; // start at head let output = ''; while (curr) { // while current node exists output += curr.value + ' -> '; curr = curr.next; // move to next node } output += 'null'; // end of list console.log(output); } } // Driver code const list = new LinkedList(); list.append(1); list.append(2); list.append(3); list.printList();
let curr = this.head; // start at headwhile (curr) {output += curr.value + ' -> ';curr = curr.next; // move to next nodeoutput += 'null';while (curr) {while (curr) {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 current = head;
let result = '';
while (current !== null) {
result += current.value + ' -> ';
current = current.next;
}
result += 'null';
console.log(result);let current = head;
while (current.next !== null) {
console.log(current.value);
current = current.next;
}Pass the test and this pattern moves unknown