Python program that inserts a new node at the beginning of a circular linked list:

Created with Sketch.

Python program that inserts a new node at the beginning of a circular linked 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 insert_at_start(self, data):
        new_node = Node(data)
        current = self.head
        new_node.next = current
        while current.next != self.head:
            current = current.next
        current.next = new_node
        self.head = new_node

    def display(self):
        current = self.head
        if self.head:
            while current.next != self.head:
                print(current.data)
                current = current.next
            print(current.data)

# create circular linked list
cll = CircularLinkedList()

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

Leave a Reply

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