Python程序:查找双向链表中的最大值和最小值节点


当需要查找双向链表中的最大值和最小值时,需要创建一个“节点”类。在这个类中,有三个属性:节点中存在的数据,对链表中下一个节点的访问,以及对链表中前一个节点的访问。

下面是一个演示:

示例

 在线演示

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(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 min_node(self):
      curr = self.head
      if(self.head == None):
         print("The list is empty")
         return 0
      else:
         min = self.head.data
         while(curr != None):
            if(min > curr.data):
               min = curr.data
            curr = curr.next
         return min
   def max_node(self):
      curr = self.head
      if(self.head == None):
         print("The list is empty")
         return 0
      else:
         max = self.head.data
         while(curr != None):
            if(curr.data > max):
               max = curr.data
            curr = curr.next
      return max
   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 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()
print("The node with maximum value is : ")
print(my_instance.max_node())
print("The node with minimum value is : ")
print(my_instance.min_node())

输出

Elements are being added to the doubly linked list
The nodes in the doubly linked list are :
10
24
54
77
92
The node with maximum value is :
92
The node with minimum value is :
10

解释

  • 创建了“节点”类。
  • 创建了另一个具有所需属性的类。
  • 定义了一个名为“add_data”的方法,用于将数据添加到双向链表。
  • 定义了另一个名为“print_it”的方法,用于显示循环链表的节点。
  • 定义了另一个名为“max_node”的方法,用于搜索双向链表中的最大值。
  • 定义了另一个名为“min_node”的方法,用于搜索双向链表中的最小值。
  • 创建了“double_list”类的对象,并调用其方法来查找双向链表中节点的最小值和最大值。
  • 定义了一个“init”方法,将双向链表的根、头和尾节点设置为None。
  • 遍历列表,找到最大值和最小值。
  • 使用“print_it”方法在控制台中显示。

更新于:2021年3月11日

379 次浏览

开启你的职业生涯

完成课程获得认证

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