Python Program to Find Number of Occurrences of All Elements in a Linked List


When it is required to find the number of occurences of all the elements of a linked list, a method to add elements to the linked list, a method to print the elements and a method to find the occurrence of all elements in the linked list are defined.

Below is a demonstration for the same −

Example

 Live Demo

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

class LinkedList_structure:
   def __init__(self):
      self.head = None
      self.last_node = None

   def add_vals(self, data):
      if self.last_node is None:
         self.head = Node(data)
         self.last_node = self.head
      else:
         self.last_node.next = Node(data)
         self.last_node = self.last_node.next

   def print_it(self):
      curr = self.head
      while curr:
         print(curr.data)
         curr = curr.next

   def count_elem(self, key):
      curr = self.head
      count_val = 0
      while curr:
         if curr.data == key:
            count_val = count_val + 1
         curr = curr.next
      return count_val

my_instance = LinkedList_structure()
my_list = [56, 78, 98, 12, 34, 55, 0]
for elem in my_list:
   my_instance.add_vals(elem)
print('The linked list is : ')
my_instance.print_it()

key_val = int(input('Enter the data item '))
count_val = my_instance.count_elem(key_val)
print('{0} occurs {1} time(s) in the list.'.format(key_val, count_val))

Output

The linked list is :
56
78
98
12
34
55
0
Enter the data item 0
0 occurs 1 time(s) in the list.

Explanation

  • The ‘Node’ class is created.

  • Another ‘LinkedList_structure’ class with required attributes is created.

  • It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’.

  • A method named ‘add_vals’ is defined, that helps add a value to the stack.

  • Another method named ‘print_it’ is defined, that helps display the values of the linked list on the console.

  • Another method named ‘count_elem’ is defined, that helps find the occurrence of every character in the linked list.

  • An instance of the ‘LinkedList_structure’ is created.

  • A list of elements is defined.

  • The list is iterated over, and these elements are added to the linked list.

  • The elements are displayed on the console.

  • The ‘count_elem’ method is called on this linked list.

  • The output is displayed on the console.

Updated on: 14-Apr-2021

106 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements