使用遞迴查詢連結串列長度的 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 calculate_length(self): return self.length_helper_fun(self.head) def length_helper_fun(self, curr): if curr is None: return 0 return 1 + self.length_helper_fun(curr.next) my_instance = my_linked_list() my_data = input('Enter elements of the linked list ').split() for elem in my_data: my_instance.add_value(int(elem)) print('The length of the linked list is ' + str(my_instance.calculate_length()))
輸出
Enter elements of the linked list 12 45 32 67 88 0 99 The length of the linked list is 7
解釋
建立“Node”類。
建立另一個具有所需屬性的“my_linked_list”類。
它有一個“init”函式,用於將第一個元素(即“head”)初始化為“None”,並將最後一個節點初始化為“None”。
定義另一個名為“add_value”的方法,用於向連結串列新增資料。
定義另一個名為“calculate_length”的方法,用於呼叫輔助函式來查詢連結串列的長度。
由於這裡需要使用遞迴,因此定義了輔助函式。
它檢查節點的當前值,並返回列表的長度。
建立“my_linked_list”類的物件。
獲取連結串列中元素的使用者輸入。
在其上呼叫方法以新增資料。
呼叫calculate_length方法,並在控制檯上顯示輸出。
廣告