Python程序在双向链表中间插入新节点


当需要在双向链表中间插入一个新节点时,需要创建一个“Node”类。在这个类中,有三个属性:节点中存在的数据、对链表中下一个节点的访问以及对链表中前一个节点的访问。

下面是对此的演示 -

示例

 在线演示

class Node:
   def __init__(self, my_data):
      self.previous = 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
      self.size = self.size + 1
   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 add_data_in_middle(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:
         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;
         temp = curr.next;
         temp.previous = curr;
         curr.next = new_node;
         new_node.previous = curr;
         new_node.next = temp;
         temp.previous = new_node;
      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)
print("Elements are added to the middle of the list")
my_instance.add_data_in_middle(77)
my_instance.print_it()
my_instance.add_data_in_middle(92)
my_instance.print_it()

输出

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

解释

  • 创建“Node”类。
  • 创建另一个具有所需属性的类。
  • 定义了一个名为“add_data_in_middle”的方法,用于在双向链表的中间索引添加数据。
  • 定义了一个名为“add_data”的方法,用于帮助将节点添加到双向链表中。
  • 定义了另一个名为“print_it”的方法,用于显示循环链表的节点。
  • 创建“double_list”类的对象,并在其上调用方法以将数据添加到双向链表中。
  • 调用“add_data_in_middle”以将数据添加到链表的中间索引。
  • 定义了一个“init”方法,将双向链表的根、头和尾节点设置为None。
  • 使用“print_it”方法在控制台上显示此内容。

更新于: 2021年3月11日

238 次浏览

开启你的职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.