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): 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.
解釋
建立“節點”類。
建立另一個名為“my_linked_list”的類,其中包含所需的屬性。
它包含一個“init”函式,用於初始化第一個元素,即“head”為“None”,最後一個節點為“None”。
定義另一個名為“add_value”的方法,用於向連結串列新增資料。
定義另一個名為“print_it”的方法,用於遍歷連結串列並列印元素。
定義另一個名為“count_val”的方法,用於查詢特定元素在連結串列中出現的頻率。
建立一個“my_linked_list”類的物件。
呼叫count_val方法,查詢特定元素的頻率。
該輸出顯示在控制檯上。
廣告