Python程序:查找链表中所有元素出现的次数


当需要查找链表中所有元素出现的次数时,需要定义一个向链表添加元素的方法,一个打印元素的方法和一个查找链表中所有元素出现次数的方法。

下面是一个演示:

示例

 在线演示

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

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

   def add_vals(self, data):
      if self.last_node is None:
         self.head = Node(data)
         self.last_node = self.head
      else:
         self.last_node.next = Node(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_elem(self, key):
      curr = self.head
      count_val = 0
      while curr:
         if curr.data == key:
            count_val = count_val + 1
         curr = curr.next
      return count_val

my_instance = LinkedList_structure()
my_list = [56, 78, 98, 12, 34, 55, 0]
for elem in my_list:
   my_instance.add_vals(elem)
print('The linked list is : ')
my_instance.print_it()

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

输出

The linked list is :
56
78
98
12
34
55
0
Enter the data item 0
0 occurs 1 time(s) in the list.

解释

  • 创建了“Node”类。

  • 创建了另一个名为“LinkedList_structure”的类,其中包含必要的属性。

  • 它有一个“init”函数,用于将第一个元素(即“head”)初始化为“None”。

  • 定义了一个名为“add_vals”的方法,用于向链表添加值。

  • 定义了另一个名为“print_it”的方法,用于在控制台上显示链表的值。

  • 定义了另一个名为“count_elem”的方法,用于查找链表中每个元素出现的次数。

  • 创建了“LinkedList_structure”的一个实例。

  • 定义了一个元素列表。

  • 遍历列表,并将这些元素添加到链表中。

  • 在控制台上显示元素。

  • 在这个链表上调用“count_elem”方法。

  • 在控制台上显示输出。

更新于:2021年4月14日

浏览量:129

开启你的职业生涯

完成课程获得认证

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