【问题标题】:Finding the length of a linked list in python在python中查找链表的长度
【发布时间】:2015-09-28 18:31:04
【问题描述】:
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
    """

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

【问题讨论】:

  • 这引出了一个问题为什么你想用一种已经原生列表和迭代方法的语言创建链接列表超过他们?

标签: python-3.x linked-list


【解决方案1】:

你也可以这样用:

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

【讨论】:

    【解决方案2】:

    "Functional linked lists in 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
    

    头尾分别是:

    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)
    

    【讨论】:

    • 所以你将 1 添加到 length(tail(xs)) 以递归地执行它,以便找到你如何进行迭代,对吗?
    • 正是如此。它就像一个柜台。
    • 当您复制他人的文字时,您必须将复制的文字放在块引号内,以表明这些不是您的文字。参考链接必须在引用的文本之前。我已更正上述内容,但请确保您在未来提供正确的归属。
    【解决方案3】:

    试试这个:

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

    【讨论】:

      【解决方案4】:

      仅供参考:2 行 Python sn-ps 计算单链表的长度

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-22
        • 2016-12-20
        • 2020-12-09
        • 1970-01-01
        相关资源
        最近更新 更多