使用递归计算链表中元素出现次数的 Python 程序


当需要使用递归来计算链表中特定元素出现的次数时,需要定义一个向链表添加元素的方法、一个打印链表元素的方法和一个计算链表中元素出现次数的方法。由于使用了递归,因此定义了一个辅助函数。此辅助函数调用之前定义的出现次数计数函数。

下面是演示 −

示例

 实时演示

class Node:
   def __init__(self, data):
      self.data = data
      self.next = None

class my_linked_list:
   def __init__(self):
      self.head = None
      self.last_node = None

   def add_value(self, my_data):
      if self.last_node is None:
         self.head = Node(my_data)
         self.last_node = self.head
      else:
         self.last_node.next = Node(my_data)
      self.last_node = self.last_node.next

   def print_it(self):
      curr = self.head
      while curr:
         print(curr.data)
         curr = curr.next

   def count_val(self, key):
      return self.count_helper_fun(self.head, key)

   def count_helper_fun(self, curr, key):
      if curr is None:
         return 0

      if curr.data == key:
         return 1 + self.count_helper_fun(curr.next, key)
      else:
         return self.count_helper_fun(curr.next, key)

my_instance = my_linked_list()
my_list = [56, 43, 70, 67, 89, 91, 70, 23, 46, 70]
for elem in my_list:
   my_instance.add_value(elem)
print("The linked list contains the below elements:")
my_instance.print_it()

key_val = int(input('Enter the data item: '))
count_val = my_instance.count_val(key_val)
print('{0} occurs {1} time(s) in the list.'.format(key_val, count_val))

输出

The linked list contains the below elements:
56
43
70
67
89
91
70
23
46
70
Enter the data item: 70

70 occurs 3 time(s) in the list.

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

解释

  • 创建“Node”类。

  • 创建另一个具有所需属性的“my_linked_list”类。

  • 它有一个“init”函数,用于初始化第一个元素,即“head”为“None”,最后一个节点为“None”。

  • 定义另一个名为“add_value”的方法,用于向链表添加数据。

  • 定义另一个名为“print_it”的方法,迭代列表并打印元素。

  • 定义另一个名为“count_val”的方法,用于调用辅助函数。

  • 定义另一个名为“count_helper_fun”的辅助函数,用于帮助确定特定元素在链表中出现的频率。

  • 创建“my_linked_list”类的对象。

  • 调用count_val方法以查找特定元素的频率。

  • 此输出显示在控制台上。

更新于: 2021年4月14日

377 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告