When it is required to insert a new node at the beginning of a circular linked list, a 'Node' class needs to be created. 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 class needs to be created that would have an initialization function, and the head of the node would be initialized to 'None'.
Multiple methods are defined by the user to add node at the beginning of the linked list, and to print the node values.
Below is a demonstration for the same −
class Node: def __init__(self,data): self.data = data self.next = None class list_creation: def __init__(self): self.head = Node(None) self.tail = Node(None) self.head.next = self.tail self.tail.next = self.head def add_at_beginning(self,my_data): new_node = Node(my_data); if self.head.data is None: self.head = new_node; self.tail = new_node; new_node.next = self.head; else: temp = self.head; new_node.next = temp; self.head = new_node; self.tail.next = self.head; def print_it(self): curr = self.head; if self.head is None: print("The list is empty"); return; else: print(curr.data), while(curr.next != self.head): curr = curr.next; print(curr.data), print("\n"); class circular_linked_list: my_cl = list_creation() print("Values are being added to the list") my_cl.add_at_beginning(21); my_cl.print_it(); my_cl.add_at_beginning(53); my_cl.print_it(); my_cl.add_at_beginning(76); my_cl.print_it();
Values are being added to the list 21 53 21 76 53 21