DSA — Circular Linked Lists
What is a Circular Linked List?
A linked list where the last node points back to the first node.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = None
Insert at End
def insert(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
new_node.next = self.head
return
current = self.head
while current.next != self.head:
current = current.next
current.next = new_node
new_node.next = self.head
Delete by Value
def delete(self, data):
if not self.head:
return
if self.head.data == data:
if self.head.next == self.head:
self.head = None
else:
current = self.head
while current.next != self.head:
current = current.next
current.next = self.head.next
self.head = self.head.next
return
current = self.head
while current.next != self.head:
if current.next.data == data:
current.next = current.next.next
return
current = current.next
Display
def display(self):
if not self.head:
return
current = self.head
while True:
print(current.data, end=" -> ")
current = current.next
if current == self.head:
break
print("(back to head)")
Mini Practice
- Implement a circular linked list
- Insert and delete nodes
- Traverse the circular list
- Detect if a list is circular
Up Next
Continue with Stacks — stack data structure.
Related Topics
Frequently Asked Questions about Circular Linked Lists
What is Circular Linked Lists in DSA?
Circular Linked Lists is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Circular Linked Lists?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Circular Linked Lists.
Why is Circular Linked Lists important in DSA?
Circular Linked Lists is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.