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

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 −


Live Demo

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

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

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

   head_ref = ptr_1
   return head_ref

def count_node(head):
   temp = head
   result = 0
   if (head != None) :
      while True :
         temp =
         result = result + 1
         if (temp == head):
   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 : ")


Elements are added to list
The number of nodes are :


  • 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.

Updated on: 13-Mar-2021


Kickstart Your Career

Get certified by completing the course

Get Started