Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to insert a new node at the beginning of the Circular Linked List
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. Instead, the last node points back to the first node.
Node Class Structure
First, we create a Node class to represent individual elements ?
class Node:
def __init__(self, data):
self.data = data
self.next = None
Circular Linked List Implementation
The main class handles the circular linked list operations ?
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = None
self.tail = None
def add_at_beginning(self, data):
new_node = Node(data)
if self.head is None:
# First node in the list
self.head = new_node
self.tail = new_node
new_node.next = self.head
else:
# Insert at beginning
new_node.next = self.head
self.head = new_node
self.tail.next = self.head
def display(self):
if self.head is None:
print("The list is empty")
return
current = self.head
result = []
while True:
result.append(str(current.data))
current = current.next
if current == self.head:
break
print(" -> ".join(result))
# Example usage
cll = CircularLinkedList()
print("Adding values to the circular linked list:")
cll.add_at_beginning(21)
cll.display()
cll.add_at_beginning(53)
cll.display()
cll.add_at_beginning(76)
cll.display()
Adding values to the circular linked list: 21 53 -> 21 76 -> 53 -> 21
How It Works
The add_at_beginning() method works in two scenarios:
- Empty list: The new node becomes both head and tail, pointing to itself
- Non-empty list: The new node points to the current head, becomes the new head, and the tail is updated to point to the new head
Visual Representation
Key Points
- The tail always points to the head in a circular linked list
- When inserting at the beginning, update both head and tail references
- The first node insertion creates a self-referencing loop
- Time complexity is O(1) for insertion at the beginning
Conclusion
Inserting at the beginning of a circular linked list requires careful handling of head and tail pointers. The key is maintaining the circular connection where the tail always points back to the head, ensuring the circular structure is preserved.
