在python中查找链表的长度

d'c*_*ang 2 linked-list python-3.x

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
    """
Run Code Online (Sandbox Code Playgroud)

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

小智 5

你也可以使用这个:

def len_link(list):
    temp=list.head
    count=0
    while(temp):
        count+=1
        temp=temp.next
    return count
Run Code Online (Sandbox Code Playgroud)


Abh*_*Dey 0

正如《Python 中的函数式链表》中所述:

长度运算返回给定列表中的元素数量。为了找到列表的长度,我们需要扫描它的所有 n 个元素。因此该操作的时间复杂度为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
Run Code Online (Sandbox Code Playgroud)

头和尾分别为:

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)
Run Code Online (Sandbox Code Playgroud)