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 l
def length(testVariable, head) :
# Base case
if (not head) :
return 0
# Recursive case
else :
return 1 + length(testVariable, head.next)
# Driver Code
myLinkedList = 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 will be the situation when a linked list contains no nodes. In this case, we will be returning 00 as the length of the linked list.

For the recursive case, we will move the head pointer to its next node, i.e., head.next, and call another instance of the same function recursively. When this child function will return add 11 to the result.

Our solution is based on the premise that: lengthofalinkedlist=1+lengthofalinkedlistwithheadpointermovedonestepaheadlength \: of \: a \: linked \: list = 1 + length \: of \: a \: linked \: list \: with \: head \:pointer \: moved \:one \: step\: ahead.

Let’s dry run our code:


In the next lesson, we have another challenge for you to solve.