简体   繁体   English

链表的Python总和

[英]Python Sum of Linked List

These are my code 这些是我的代码

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

Problem is at the end of the code 问题在代码末尾

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

If i try this 如果我尝试这个

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

I don't understand why it said 我不明白为什么这么说

builtins.AttributeError: 'int' object has no attribute 'data' Builtins.AttributeError:'int'对象没有属性'data'

The while loop works until it reach the last node while循环有效,直到到达最后一个节点

result should be 6 结果应该是6

Because 3 is your next node. 因为3是您的下一个节点。 You probably wanted something like: 您可能想要类似的东西:

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

You are pointing to a node at the end which does not exist. 您指向的节点不存在。 The second nested node points to a next node 3, but that node does not exist sow hen it goes to look for its data, it is nowhere to be found. 第二个嵌套节点指向下一个节点3,但是该节点不存在,因此当它查找其数据时,找不到该节点。

How about a different approach; 如何使用不同的方法; create an iterator to iterate through the linked list. 创建一个迭代器来迭代链表。 Then you've got a standard iterator and you can just sum it with the builtin sum function: 然后,您有了一个标准的迭代器,您可以使用内置的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