Python program to create a Circular Linked List of N nodes and count the number of nodes

PythonServer Side ProgrammingProgramming

When it is required to create a circular linked list that has 'N' nodes, and get the count of the number of nodes, a 'Node' class needs to be created. To display the data elements in the circular list, another method can be defined, that would display the data. In this class, there are two attributes, the data that is present in the node, and the access to the next node of the linked list. In a circular linked list, the head and the rear are adjacent to each other.

They are connected to form a circle, and don't have 'NULL' value in the last node.

Another 'linked_list' class needs to be created that would have an initialization function, and the head of the node would be initialized to 'None'. 

Below is a demonstration for the same −

Example

Live Demo

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

def add_data(head_ref,my_data):
   ptr_1 = Node(0)
   temp = head_ref
   ptr_1.data = my_data
   ptr_1.next = head_ref

   if (head_ref != None) :
      while (temp.next != head_ref):
         temp = temp.next
      temp.next = ptr_1
   else:
      ptr_1.next = ptr_1

   head_ref = ptr_1
   return head_ref

def count_node(head):
   temp = head
   result = 0
   if (head != None) :
      while True :
         temp = temp.next
         result = result + 1
         if (temp == head):
            break  
   return result

if __name__=='__main__':
   head = None
   head = add_data(head, 78)
   head = add_data(head, 56)
   head = add_data(head, 22)
   print("Elements are added to list")
   print("The number of nodes are : ")
   print(count_node(head))

Output

Elements are added to list
The number of nodes are :
3

Explanation

  • The 'Node' class is created.
  • Another 'linked_list' class with required attributes is created.
  • Another method named 'add_data' is defined, that is used to add data to the circular linked list.
  • Another method named 'print_it' is defined that is used to display the linked list data on the console.
  • An object of the 'linked_list' class is created, and the methods are called on it to add data.
  • This is displayed on the console using the 'print_it' method.
raja
Published on 13-Mar-2021 05:50:33
Advertisements