繁体   English   中英

链表的Python总和

[英]Python Sum of Linked List

这些是我的代码

class Node():
'''A node in a linked list'''
    def __init__(self, data, next_node=None):
        self.data = data
        self.next_node = next_node


def sum(LL):

    head = LL

    # If Linked list is empty, return 0
    if (head.data is None or head.data == []):
        result = 0

    # If Linked List contain only 1 node then return it
    elif (head.next_node is None):
        result = head.data

    else:
        curr = head
        result = curr.data
        # If next is not None then add up to result
        while (curr.next_node is not None):
            curr = curr.next_node
            result += curr.data

    return result

问题在代码末尾

while (curr.next_node is not None):
    curr = curr.next_node
    result += curr.data

如果我尝试这个

LL = Node(1, Node(2, 3))
sum(LL)

我不明白为什么这么说

Builtins.AttributeError:'int'对象没有属性'data'

while循环有效,直到到达最后一个节点

结果应该是6

因为3是您的下一个节点。 您可能想要类似的东西:

LL = Node(1, Node(2, Node(3)))

您指向的节点不存在。 第二个嵌套节点指向下一个节点3,但是该节点不存在,因此当它查找其数据时,找不到该节点。

如何使用不同的方法; 创建一个迭代器来迭代链表。 然后,您有了一个标准的迭代器,您可以使用内置的sum函数对其求和:

def traverse(LL):
    head = LL
    while (head):
        yield head.data
        head = head.next_node


sum(traverse(LL))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM