Python程序:在循环链表中间插入新节点
需要在循环链表中间插入一个新节点时,需要创建一个名为“节点(Node)”的类。在这个类中,有两个属性:节点中存在的数据以及对链表中下一个节点的访问。
在循环链表中,表头和表尾彼此相邻。它们连接成一个环,最后一个节点没有“NULL”值。
需要创建另一个类,该类将具有一个初始化函数,并且节点的头将初始化为“None”。
用户定义了多个方法来在链表中间添加节点以及打印节点值。
下面是对此的演示:
示例
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;
if self.head is 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
解释
- 创建“节点(Node)”类。
- 创建另一个具有所需属性的类。
- 定义另一个名为“add_in_between”的方法,用于在循环链表的中间(即中间位置)添加数据。
- 定义另一个名为“print_it”的方法,用于显示循环链表的节点。
- 创建“list_creation”类的对象,并在其上调用方法以添加数据。
- 定义一个“init”方法,将循环链表的第一个和最后一个节点设置为None。
- 调用“add_in_between”方法。
- 它遍历列表,获取中间索引并在该位置插入元素。
- 使用“print_it”方法在控制台上显示此内容。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP