3.
Write a program to implement circular linked list as an ADT which
supports the following operations:
i. Insert an element x in the list
ii. Remove an element from the list
iii. Search for an element x in the list and return its pointer
CODE
class Node:
"""A class to represent a node in a circular linked list."""
def __init__(self, data):
[Link] = data
[Link] = None
class CircularLinkedList:
"""A class to represent a circular linked list."""
def __init__(self):
[Link] = None # Tail points to the last node in the
circular list.
def is_empty(self):
"""Check if the list is empty."""
return [Link] is None
def insert(self, x):
"""Insert an element x into the circular linked list."""
new_node = Node(x)
if self.is_empty():
# If the list is empty, point the new node to itself.
[Link] = new_node
[Link] = new_node
else:
# Insert the new node after the current tail and update the
tail.
new_node.next = [Link]
[Link] = new_node
[Link] = new_node
print(f"Inserted {x} into the list.")
def remove(self, x):
"""Remove an element x from the circular linked list."""
if self.is_empty():
print("The list is empty! Nothing to remove.")
return
current = [Link] # Start at the head of the list.
prev = [Link]
while True:
if [Link] == x:
if current == [Link] and [Link] == [Link]:
# The list has only one node.
[Link] = None
else:
# Remove the current node by updating pointers.
[Link] = [Link]
if current == [Link]:
[Link] = prev # Update tail if the last
node is removed.
print(f"Removed {x} from the list.")
return
prev = current
current = [Link]
if current == [Link]:
# Completed one full cycle, element not found.
print(f"Element {x} not found in the list.")
return
def search(self, x):
"""Search for an element x in the circular linked list and
return its pointer."""
if self.is_empty():
print("The list is empty! Cannot search.")
return None
current = [Link] # Start at the head of the list.
while True:
if [Link] == x:
print(f"Element {x} found in the list.")
return current
current = [Link]
if current == [Link]:
# Completed one full cycle, element not found.
print(f"Element {x} not found in the list.")
return None
def display(self):
"""Display all elements in the circular linked list."""
if self.is_empty():
print("The list is empty.")
return
current = [Link] # Start at the head of the list.
elements = []
while True:
[Link]([Link])
current = [Link]
if current == [Link]:
break
print("List:", " -> ".join(map(str, elements)))
# Example usage of the circular linked list
if __name__ == "__main__":
cll = CircularLinkedList()
[Link](10)
[Link](20)
[Link](30)
[Link]()
[Link](20)
[Link](20)
[Link]()
[Link](40) # Element not in the list
[Link](40)
OUTPUT