Python程序:删除双向链表中间的新节点
当需要从双向链表中间删除节点时,需要创建一个“节点”类。在这个类中,有三个属性:节点中存在的数据、对链表中下一个节点的访问以及对链表中上一个节点的访问。
需要创建另一个类,该类将具有初始化函数,并且节点的头在其中初始化为“None”。
用户定义了多个方法来向链表添加节点、显示节点以及从双向链表的末尾删除节点。
在双向链表中,节点具有指针。当前节点将指向下一个节点和上一个节点。列表中的最后一个值在下一个指针中将具有“NULL”值。它可以双向遍历。
下面是对此的演示 -
示例
class Node:
def __init__(self, my_data):
self.prev = None
self.data = my_data
self.next = None
class double_list:
def __init__(self):
self.head = None
self.tail = None
self.size = 0;
def add_data(self, my_data):
new_node = Node(my_data)
if(self.head == None):
self.head = self.tail = new_node;
self.head.previous = None;
self.tail.next = None;
else:
self.tail.next = new_node;
new_node.previous = self.tail;
self.tail = new_node;
self.tail.next = None;
def print_it(self):
curr = self.head
if (self.head == None):
print("The list is empty")
return
print("The nodes in the doubly linked list are :")
while curr != None:
print(curr.data)
curr = curr.next
def delete_from_middle(self):
if(self.head == None):
return;
else:
curr = self.head
mid = (self.size//2) if(self.size % 2 == 0) else((self.size+1)//2)
for i in range(1, mid):
curr = curr.next;
if(curr == self.head):
self.head = curr.next
self.tail.next = None
elif(curr == self.tail):
self.tail = self.tail.prev;
else:
curr.prev.next = curr.next;
curr.next.prev = curr.prev;
current = None;
self.size = self.size - 1;
my_instance = double_list()
print("Elements are being added to the doubly linked list")
my_instance.add_data(10)
my_instance.add_data(24)
my_instance.add_data(54)
my_instance.add_data(77)
my_instance.add_data(92)
my_instance.print_it()
while(my_instance.head != None):
my_instance.delete_from_middle();
print("The list after deleting the element from the middle is : ")
my_instance.print_it();输出
Elements are being added to the doubly linked list The nodes in the doubly linked list are : 10 24 54 77 92 The list after deleting the element from the middle is : The nodes in the doubly linked list are : 24 54 77 92 The list after deleting the element from the middle is : The nodes in the doubly linked list are : 54 77 92 The list after deleting the element from the middle is : The nodes in the doubly linked list are : 77 92 The list after deleting the element from the middle is : The nodes in the doubly linked list are : 92 The list after deleting the element from the middle is : The list is empty
解释
- 创建“节点”类。
- 创建另一个具有所需属性的类。
- 定义了一个名为“add_data”的方法,用于向双向链表添加数据。
- 定义了另一个名为“print_it”的方法,用于显示循环链表的节点。
- 定义了另一个名为“delete_from_middle”的方法,用于从中间删除节点,并将上一个节点设为循环链表中的当前节点。
- 创建“double_list”类的对象,并在其上调用方法以从双向链表的开头删除节点。
- 定义了一个“init”方法,将双向链表的根、头和尾节点设置为None。
- 迭代列表,并删除链表中间索引的每个节点,直到为空。
- 使用“print_it”方法在控制台中显示。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP