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

pythonserver side programmingprogramming更新于 2023/12/27 4:06:00

当需要不使用递归计算链接列表中特定元素出现次数时,需要定义一种将元素添加到链接列表的方法、一种显示链接列表元素的方法以及一种计算值出现次数的方法。

下面是同样的演示 −

示例

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):
      curr = self.head
      my_count = 0
      while curr:
         if curr.data == key:
            my_count = my_count + 1
         curr = curr.next
      return my_count

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.

解释

  • 创建了 ‘Node’ 类。

  • 创建了另一个具有必需属性的 ‘my_linked_list’ 类。

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

  • 定义了另一个名为 ‘add_value’ 的方法,用于将数据添加到链接列表中。

  • 定义了另一个名为 ‘print_it’ 的方法,该方法遍历列表并打印元素。

  • 另一个名为 ‘count_val’ 的方法被定义用于查找链接列表中特定元素的出现频率。

  • 创建 ‘my_linked_list’ 类的对象。

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

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


相关文章