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

pythonserver side programmingprogramming

当需要查找链接列表中所有元素的出现次数时,需要定义一种将元素添加到链接列表的方法、一种打印元素的方法以及一种查找链接列表中所有元素出现次数的方法。

下面是同样的演示 −

示例

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’ 方法。

  • 输出显示在控制台上。


相关文章