使用递归查找链表长度的 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): ifself.last_nodeis 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
解释
创建了“节点”类。
创建了另一个具有必需属性的“my_linked_list”类。
它有一个“init”函数,用于初始化第一个元素,i.e“head”为“None”,最后一个节点为“None”。
定义了另一个名为“add_value”的方法,用于向链表添加数据。
定义了另一个名为“calculate_length”的方法,用于调用辅助函数来查找链表的长度。
定义了辅助函数,因为这里需要使用递归。
它检查节点的当前值,并返回列表的长度。
创建了“my_linked_list”类的对象。
用户输入用于链表中的元素。
在其上调用方法来添加数据。
调用calculate_length方法,并在控制台上显示输出。