A Circular Linked List is a variation of a linked list where the last node points back to the first node, forming a circular loop.
NULL
.class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.last = None
def addToEmpty(self, data):
if self.last is not None:
return self.last
newNode = Node(data)
self.last = newNode
self.last.next = self.last
return self.last
def addFront(self, data):
if self.last is None:
return self.addToEmpty(data)
newNode = Node(data)
newNode.next = self.last.next
self.last.next = newNode
return self.last
def traverse(self):
if self.last is None:
print("List is empty")
return
temp = self.last.next
while True:
print(temp.data, end=" ")
temp = temp.next
if temp == self.last.next:
break
# Usage
cll = CircularLinkedList()
cll.addToEmpty(5)
cll.addFront(4)
cll.addFront(3)
cll.traverse() # Output: 3 4 5
This basic example creates and traverses a circular singly linked list in Python.