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...
We'll cover the following...
Solution: Using Recursion
Explanation
Have a look at the function length() in index.js file.
The base case (line number 5 to 7) for this problem is when a linked list contains no nodes. In this case, we return as the length of that linked list.
For the recursive case (line number 11), we move the head pointer to its next node, head.next, and call another instance of the same function recursively. When this child function returns, we add to the result.
Our solution is based on the following premise: ...