Python-运用递归计算链表节点数

Python
在单链表中如何使用递归思想统计一个链表的节点数?

1.任何循环都可以改写为递归的形式
2.链表不就是不断的next一直到结尾吗

def length(link,n):
    if link:
        return length(link.next,n+1)
    else:
        return n

def length(link):
    if link:
        return 1 + length(link.next)
    else:
        return 0

单链表实现及递归计算链表节点数:

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()))


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

输出结果:

Enter elements of the linked list 12 45 32 67 88 0 99
The length of the linked list is 7

Process finished with exit code 0