無需遞迴查詢連結串列長度的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): curr = self.head length_val = 0 while curr: length_val = length_val + 1 curr = curr.next return length_val 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 34 12 56 86 32 99 0 6 The length of the linked list is 8
解釋
建立了“Node”類。
建立了另一個名為“my_linked_list”的類,其中包含所需的屬性。
它有一個“init”函式,用於將第一個元素(即“head”)初始化為“None”,並將最後一個節點初始化為“None”。
定義了另一個名為“add_value”的方法,用於向連結串列新增資料。
定義了另一個名為“calculate_length”的方法,用於查詢連結串列的長度。
建立了“my_linked_list”類的物件。
獲取使用者輸入以獲取連結串列中的元素。
呼叫方法向其中新增資料。
呼叫calculate_length方法來查詢列表的長度。
此輸出顯示在控制檯上。
廣告