使用遞迴計算連結串列中元素出現次數的 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): return self.count_helper_fun(self.head, key) def count_helper_fun(self, curr, key): if curr is None: return 0 if curr.data == key: return 1 + self.count_helper_fun(curr.next, key) else: return self.count_helper_fun(curr.next, key) 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”的方法,用於呼叫輔助函式。
定義另一個名為“count_helper_fun”的輔助函式,用於幫助確定特定元素在連結串列中出現的頻率。
建立“my_linked_list”類的物件。
呼叫count_val方法以查詢特定元素的頻率。
此輸出顯示在控制檯上。
廣告