Solution Review: Length of a Linked List
This review provides a detailed analysis of the solution to find the length of a linked list.
We'll cover the following...
Solution: Using Recursion
Press + to interact
main.py
linkedList.py
node.py
import linkedList as ldef length(testVariable, head) :# Base caseif (not head) :return 0# Recursive caseelse :return 1 + length(testVariable, head.next)# Driver CodemyLinkedList = l.LinkedList()myLinkedList.append(3)myLinkedList.append(4)myLinkedList.append(7)myLinkedList.append(11)print(length(myLinkedList, myLinkedList.head))
Explanation
The base case 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, 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: ...