当需要在循环链表的中间插入新节点时,需要创建一个“节点”类。在此类中,有两个属性,即节点中存在的数据和对链表的下一个节点的访问。
在圆形链表中,头部和后部彼此相邻。它们连接形成一个圆,并且在最后一个节点中没有'NULL'值。
需要创建另一个具有初始化功能的类,并将节点的头初始化为“无”。
用户定义了多种方法,可在链接列表之间添加节点并打印节点值。
以下是相同的演示-
class Node:
def __init__(self,data):
self.data= data
self.next= None
class list_creation:
def __init__(self):
self.head= Node(None)
self.tail= Node(None)
self.head.next =self.tail
self.tail.next =self.head
self.size= 0;
def add_data(self,my_data):
new_node = Node(my_data)
if self.head.data is None:
self.head = new_node
self.tail = new_node
new_node.next =self.head
else:
self.tail.next = new_node
self.tail = new_node
self.tail.next = self.head
self.size= self.size+1
def add_in_between(self,my_data):
new_node = Node(my_data);
if(self.head == None):
self.head = new_node;
self.tail = new_node;
new_node.next = self.head;
else:
count = (self.size//2) if (self.size % 2 == 0) else ((self.size+1)//2);
temp = self.head;
for i in range(0,count):
curr = temp;
temp = temp.next;
curr.next = new_node;
new_node.next = temp;
self.size= self.size+1;
def print_it(self):
curr = self.head;
ifself.headis None:
print("The list is empty");
return;
else:
print(curr.data)
while(curr.next != self.head):
curr = curr.next;
print(curr.data)
print("\n");
class circular_linked_list:
my_cl = list_creation()
print("Nodes are being added to the list")
my_cl.add_data(21)
my_cl.add_data(54)
my_cl.add_data(78)
my_cl.add_data(99)
print("The list is :")
my_cl.print_it();
my_cl.add_in_between(33);
print("The updated list is :")
my_cl.print_it();
my_cl.add_in_between(56);
print("The updated list is :")
my_cl.print_it();
my_cl.add_in_between(0);
print("The updated list is :")
my_cl.print_it();输出结果Nodes are being added to the list The list is : 21 54 78 99 The updated list is : 21 54 33 78 99 The updated list is : 21 54 33 56 78 99 The updated list is : 21 54 33 0 56 78 99
将创建“节点”类。
创建具有必需属性的另一个类。
定义了另一个名为“ add_in_between”的方法,该方法用于将数据添加到i.e中间最中间位置的循环链表中。
定义了另一个名为“ print_it”的方法,该方法显示循环链接列表的节点。
创建“ list_creation”类的对象,并在其上调用方法以添加数据。
定义了一个“ init”方法,该方法将循环链表的第一个和最后一个节点设置为None。
调用“ add_in_between”方法。
遍历列表,获取最中间的索引,然后将元素插入此位置。
这使用“ print_it”方法显示在控制台上。