0

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'

The while loop works until it reach the last node

result should be 6

0

3 Answers 3

3

Because 3 is your next node. You probably wanted something like:

LL = Node(1, Node(2, Node(3)))
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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:

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


sum(traverse(LL))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.