Search⌘ K
AI Features

Solution Review: Length of a Linked List

Explore how to calculate the length of a linked list using a recursive function. Learn the base and recursive cases with a step-by-step code walkthrough to deepen your understanding of recursion with linked data structures.

We'll cover the following...

Solution: Using Recursion

Javascript (babel-node)
import LinkedList from './linkedList.js'
function length(testVariable, head) {
// Base case
if (head == null) {
return 0;
}
// Recursive case
else {
return 1 + length(testVariable, head.next);
}
}
// Driver Code
var list = new LinkedList();
list.appendNode(4);
list.appendNode(3);
list.appendNode(11);
list.appendNode(7);
console.log(length(list, list.head))

Explanation

Have a look at the ...