Python程序:在双向链表头部插入新节点


需要在双向链表的头部插入一个新节点时,需要创建一个名为“Node”的类。在这个类中,有三个属性:节点中存在的数据、指向链表中下一个节点的访问权限以及指向链表中上一个节点的访问权限。

下面是一个演示:

示例

 在线演示

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
   def add_data_at_start(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.previous = new_node
         new_node.next = self.head
         new_node.previous = None
         self.head = new_node
   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
my_instance = double_list()
print("Elements are being added to the beginning of doubly linked list")
my_instance.add_data_at_start(10)
my_instance.print_it()
my_instance.add_data_at_start(24)
my_instance.print_it()
my_instance.add_data_at_start(54)
my_instance.print_it()
my_instance.add_data_at_start(77)
my_instance.print_it()
my_instance.add_data_at_start(92)
my_instance.print_it()

输出

Elements are being added to the beginning of doubly linked list
The nodes in the doubly linked list are :
10
The nodes in the doubly linked list are :
24
10
The nodes in the doubly linked list are :
54
24
10
The nodes in the doubly linked list are :
77
54
24
10
The nodes in the doubly linked list are :
92
77
54
24
10

解释

  • 创建了“Node”类。
  • 创建了另一个包含所需属性的类。
  • 定义了一个名为“add_data_at_start”的方法,用于在双向链表的开头添加数据。
  • 定义了另一个名为“print_it”的方法,用于显示循环链表的节点。
  • 创建了“double_list”类的对象,并在其上调用方法以在双向链表的开头添加数据。
  • 定义了一个“init”方法,将双向链表的根、头和尾节点设置为None。
  • 遍历列表,并将元素添加到双向链表的开头。
  • 使用“print_it”方法在控制台上显示结果。

更新于:2021年3月11日

浏览量:342

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.