In this lesson, we’ll calculate the length or the number of nodes in a given linked list. We’ll be doing this in both an iterative and recursive manner.
Algorithm
Let’s look at a linked list and recall how we managed to print out the elements of a linked list. We iterate through every element of the linked list. We start from the head node and while we don’t reach None, we print the data field of the node that we point to and increment the while loop by setting the current node equal to the next node.
Singly Linked List : Print Method
A
1 of 5
Iterative Implementation
The above algorithm is going to help us construct an iterative method to calculate the length of a linked list. Let’s go ahead and create a method len_iterative and step through it.