Python程序创建包含n个节点的双向链表并统计节点数量


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

在双向链表中,节点具有指针。当前节点将拥有指向下一个节点和上一个节点的指针。列表中的最后一个值将在下一个指针中具有“NULL”值。它可以双向遍历。

以下是相同内容的演示 -

示例

 在线演示

class Node:
   def __init__(self, my_data):
      self.prev = None
      self.data = my_data
      self.next = None
class count_val:
   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 count_node(self):
      my_counter = 0;
      curr = self.head;
      while(curr != None):
         my_counter = my_counter + 1;
         curr = curr.next;
      return my_counter;
   def print_it(self):
      curr = self.head
      if (self.head == None):
         print("The list is empty")
         return
      print("The nodes are :")
      while curr != None:
         print(curr.data)
         curr = curr.next
my_instance = count_val()
print("Elements are being added to the list")
my_instance.add_data(10)
my_instance.add_data(14)
my_instance.add_data(24)
my_instance.add_data(17)
my_instance.add_data(22)
my_instance.print_it()
print("The nodes in the doubly linked list are : ")
print(my_instance.count_node())

输出

Elements are being added to the list
The nodes are :
10
14
24
17
22
The nodes in the doubly linked list are :
5

解释

  • 创建“Node”类。
  • 创建另一个具有所需属性的类。
  • 定义了一个名为“add_data”的方法,用于将数据添加到双向链表中。
  • 定义了另一个名为“count_node”的方法,该方法有助于获取双向链表中节点的数量。
  • 定义了另一个名为“print_it”的方法,该方法显示循环链表的节点。
  • 创建“count_val”类的对象,并在其上调用方法以将双向链表转换为三叉树。
  • 定义了一个“init”方法,将双向链表的根、头和尾节点设置为None。
  • 调用“count_node”方法。
  • 它遍历双向链表,并获取列表中的节点数量。
  • 使用“print_it”方法在控制台上显示此信息。

更新于: 2021年3月11日

127次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.