Python program that deletes a node from the middle of a circular linked list, given a specific value:
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = None
def append(self, data):
if not self.head:
self.head = Node(data)
self.head.next = self.head
else:
current = self.head
while current.next != self.head:
current = current.next
new_node = Node(data)
current.next = new_node
new_node.next = self.head
def delete_middle(self, value):
current = self.head
prev = None
if self.head:
while current.next != self.head:
if current.data == value:
prev.next = current.next
return
prev = current
current = current.next
if current.data == value:
prev.next = current.next
else:
raise ValueError("Value not found in the list")
def display(self):
current = self.head
if self.head:
while current.next != self.head:
print(current.data)
current = current.next
print(current.data)
# create circular linked list
cll = CircularLinkedList()
# append some data to the list
cll.append(1)
cll.append(2)
cll.append(3)
# delete the middle node with value 2
cll.delete_middle(2)
# display the updated list
cll.display()
In this example, we first define a Node class with a constructor that initializes the data and next properties. The CircularLinkedList class is implemented using the Node class. The CircularLinkedList class has an append method that adds new data to the end of the linked list, a delete_middle method that deletes a node from the middle of the linked list given a specific value and a display method that prints the data of each node in the list.
The delete_middle() method deletes a node from the middle of the circular linked list, given a specific value. It starts by initializing two variables, current and prev. current is set to the head of the linked list and prev to None. Then it iterates through the list until it finds a node with the given value. It then updates the next pointer of the previous node to point to the next node, effectively cutting the current node out of the list. If it doesn’t find the value it will raise an exception.
After calling the delete_middle method, the updated list can be displayed using the display method.
Please note that this implementation assumes the list is not empty and if the list is empty it will raise an Exception. Also, it will only delete the first node it finds with the given value, if there are multiple nodes with the same value, it will only delete the first one.