【问题标题】:Scale a (singly) Linked List by n Recursively递归地按 n 缩放(单个)链表
【发布时间】:2020-11-13 23:14:18
【问题描述】:

我正在尝试按一个因子缩放链接列表,n

例如

scale(3->5->7,2) 应该返回 6->10->14

这是我到目前为止所拥有的:(假设节点类已经定义并且它具有默认数据和下一个属性) 它只返回节点的最后一个元素乘以 n,我有点不知道下一步该做什么。

def scale(head, n):
    if head is None:
        return None
    elif head.next is None:
        return(Node(head.data * n, None))
    else:
        return scale(head.next, n)

【问题讨论】:

  • 您是在尝试返回新列表还是在原地修改列表?

标签: python algorithm recursion linked-list


【解决方案1】:

递归步骤不正确,您应该在遍历它时构建一个新列表。这应该有效:

def scale(head, n):
    if head is None:
        return None
    else:
        return Node(head.data * n, scale(head.next, n))

甚至更短,利用函数隐式返回None的事实:

def scale(head, n):
    if head: return Node(head.data * n, scale(head.next, n))

【讨论】:

    【解决方案2】:

    这很正常,因为这就是您告诉程序要做的事情。您可以尝试使用迭代方法:

    def scale(head, n):
        pointer = head
    
        while pointer.next: 
            pointer.data *= n
            pointer = pointer.next
    
        return head
    

    或者如果你坚持递归,你需要把头放在某个地方。要重用您的代码,可以这样做:

    def scale(head, n, first):
        if head is None:
            return None
        elif head.next is None:
            head = Node(head.data * n, None)
            return first
        else:
            return scale(head.next, n, first)
    

    您需要在调用时将列表的头部作为函数的第三个参数传递。 更聪明

    def scale(head, n):
        if not head:
            return None
        else:
            return Node(head.data * n, scale(head.next, n))
    

    【讨论】:

      猜你喜欢
      • 2012-11-05
      • 2021-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-27
      • 1970-01-01
      • 2020-10-02
      相关资源
      最近更新 更多