Python Program to Count the Occurrences of Elements in a Linked List using Recursion

In this Python program, we will leverage recursion to count the occurrences of elements within a linked list. This program will provide you with a deeper understanding of recursion and how it can be applied to solve problems involving linked lists.

Problem statement

The challenge is to write a Python program that counts the occurrences of elements in a given linked list using recursion. By employing recursion, you can efficiently traverse the linked list and tally the number of occurrences of each element.

Python Program to Count the Occurrences of Elements in a Linked List using Recursion

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def insert(self, data):
        new_node = Node(data)
        if not self.head:
            self.head = new_node
        else:
            current = self.head
            while current.next:
                current = current.next
            current.next = new_node

    def count_occurrences(self, head, target):
        if not head:
            return 0
        if head.data == target:
            return 1 + self.count_occurrences(head.next, target)
        else:
            return self.count_occurrences(head.next, target)

# Example usage
if __name__ == "__main__":
    linked_list = LinkedList()
    elements = [2, 4, 3, 4, 2, 5, 4]
    for element in elements:
        linked_list.insert(element)
    
    target_element = 4
    occurrences = linked_list.count_occurrences(linked_list.head, target_element)
    print(f"Occurrences of {target_element}: {occurrences}")

Input / Output

Python Program to Count the Occurrences of Elements in a Linked List using Recursion

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this python tutorial, you will learn how to Display Prime Numbers Between Two Intervals using the if and else...
In this python tutorial, you will learn how to Calculate Standard Deviation with built in functions of the python programming...
In this Python program, we will convert temperature values from Celsius to Fahrenheit. The Celsius and Fahrenheit scales are two...