Traverse a singly linked list
JavaScriptclass Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
function traverse(head) {
let current = head;
while (current !== null) {
console.log(current.data);
current = current.next;
}
}
const a = new Node(10);
const b = new Node(25);
const c = new Node(37);
a.next = b;
b.next = c;
traverse(a);Explanation
The function starts at head and keeps moving current to current.next until it becomes null. That is the standard linked-list traversal pattern. You cannot jump directly to the third node like an array index.
Output
10 25 37
Real-life Example
A music playlist where every song record stores a pointer to the next song behaves like a linked list when you keep pressing next.