Count Occurrences

In this lesson, we will learn how to count occurrences​ of a data element in a linked list.

In this lesson, we investigate how to count the occurrence of nodes with a specified data element. We will consider how one may solve this problem in both an iterative and recursive manner, and we will code the solution to both of these approaches in Python.

As an example, have a look at the illustration below where we have a linked list with the following elements:

1 - 1 - 2 - 1

You can see that the number of occurrences of 1 in the linked list is 3.

Iterative Implementation #

Our approach to iteratively solving this problem is straightforward. We’ll traverse the linked list and count the occurrences as we go along. Let’s go ahead and code it in Python!

Press + to interact
def count_occurences_iterative(self, data):
count = 0
cur = self.head
while cur:
if cur.data == data:
count += 1
cur = cur.next
return count
...