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.