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 create and display a Circular Linked List
A circular linked list is a data structure where the last node points back to the first node, forming a circle. Unlike regular linked lists that end with None, circular linked lists have no end − the traversal can continue indefinitely.
To implement a circular linked list in Python, we need two classes: a Node class to represent individual elements, and a CircularLinkedList class to manage the list operations.
Node Class Structure
Each node contains data and a reference to the next node ?
class Node:
def __init__(self, data):
self.data = data
self.next = None
Circular Linked List Implementation
Here's a complete implementation that creates and displays a circular linked list ?
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = None
def add_data(self, data):
new_node = Node(data)
if not self.head:
# First node - points to itself
self.head = new_node
new_node.next = self.head
else:
# Find the last node
current = self.head
while current.next != self.head:
current = current.next
# Insert new node at the beginning
new_node.next = self.head
current.next = new_node
self.head = new_node
def display(self):
if not self.head:
print("List is empty")
return
current = self.head
print("The circular linked list is:")
# Traverse until we come back to head
while True:
print(current.data)
current = current.next
if current == self.head:
break
# Create and populate the circular linked list
my_list = CircularLinkedList()
my_list.add_data(47)
my_list.add_data(89)
my_list.add_data(34)
my_list.add_data(11)
my_list.display()
The circular linked list is: 11 34 89 47
How It Works
The key difference from a regular linked list is in the linking logic:
-
First node: Points to itself (
new_node.next = self.head) -
Subsequent nodes: Last node's
nextalways points tohead -
Display: Uses
while Trueloop with break condition when we reachheadagain
Visualization
Key Features
- No NULL termination: Last node points to the first node
- Continuous traversal: Can loop through the list indefinitely
- Efficient insertion: New nodes added at the beginning for O(1) complexity
Conclusion
Circular linked lists are useful for applications requiring continuous cycling through data, like round-robin scheduling. The key implementation detail is ensuring the last node always points back to the head, creating the circular structure.
