Python program that creates a circular linked list of N nodes and counts the number of nodes:

Created with Sketch.

A circular linked list is a type of linked list where the last node points to the first node, forming a circular loop. Here is a Python program that creates a circular linked list of N nodes and counts the number of nodes in the list:

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

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

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

    def count(self):
        current = self.head
        count = 0
        if self.head:
            count = 1
            while current.next != self.head:
                current = current.next
                count += 1
        return count

# create circular linked list
cll = CircularLinkedList()

# append some data to the list
cll.append(1)
cll.append(2)
cll.append(3)

# count the number of nodes
print(cll.count()) # Output: 3

In this example, we first define a Node class with a constructor that initializes the data and next properties. The CircularLinkedList class is implemented using the Node class. The CircularLinkedList class has an append method that adds new data to the end of the linked list and a count method that returns the number of nodes in the list.

Leave a Reply

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