在 python 中查找链表的长度

Finding the length of a linked list in python

def len_link(lst):

"""Returns the length of the link.

    >>> lst = link(1, link(2, link(3, link(4))))
    >>> len_link(lst)
    4
    >>> len_link(empty)
    0
    """

您好,我很难理解如何找到链表的长度,如果有人能提供帮助,我将不胜感激。

"Functional linked lists in Python"所述:

The length operation returns the number of elements in a given list. To find the length of a list we need to scan all of its n elements. Therefore this operation has a time complexity of O(n).

def length(xs):
    if is_empty(xs):
        return 0
    else:
        return 1 + length(tail(xs))

assert length(lst(1, 2, 3, 4)) == 4
assert length(Nil) == 0

head and tail are respectively:

def head(xs):
    return xs[0]

assert head(lst(1, 2, 3)) == 1
def tail(xs):
    return xs[1]

assert tail(lst(1, 2, 3, 4)) == lst(2, 3, 4)

你也可以使用这个:

def len_link(list):
    temp=list.head
    count=0
    while(temp):
        count+=1
        temp=temp.next
    return count

试试这个:

def lengthRecursive(head):
    if head is None:
        return 0
    else:
       return 1 + lengthRecursive(head.next)

仅供参考:2 行 Python 片段来计算单链表的长度

# iterative
n, curr = 0, head
while curr: n, curr = n + 1, curr.next

# recursive
def length(head: ListNode):
    return 0 if not head else 1 + length(head.next)