Python program that creates a circular linked list of n nodes and displays it in reverse order:
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 reverse(self):
prev = None
current = self.head
while current:
nxt = current.next
current.next = prev
prev = current
current = nxt
self.head = prev
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)
# display the list in reverse order
cll.reverse()
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 reverse method that reverses the order of the nodes in the list, and a display method that prints the data of each node in the list. The reverse method works by changing the next pointer of each node to point to the previous node, effectively reversing the order of the nodes in the list. The display method is used to display the reversed linked list.