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 −
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))
Elements are added to list The number of nodes are : 3