簡體   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