University of Arizona, Department of Computer Science

CSc 120: Summing the elements of a linked list

Expected Behavior

Given a LinkedList object llist, the execution of the code

llist.sum()
should return the sum of the elements of llist.

The code for the LinkedList class is as follows:

class Node:
    def __init__(self, value):
        self._value = value
        self._next = None
    
    # getter for the _value attribute
    def value(self):
        return self._value
    
    # getter for the _next attribute
    def next(self):
        return self._next
        
    def __str__(self):
        return str(self._value) + "; "
    
class LinkedList:
    def __init__(self):
        self._head = None

    # add a node to the head of the list
    def add(self, node):
        node._next = self._head
        self._head = node
        
    def __str__(self):
        string = 'List[ '
        curr_node = self._head
        while curr_node != None:
            string += str(curr_node)
            curr_node = curr_node.next()
        string += ']'
        return string

Examples

  1. Code:
    ll = LinkedList()
    ll.add(Node(1))
    ll.add(Node(3))
    ll.add(Node(2))
    return ll.sum()
    Result: 6
  2. Code:
    ll = LinkedList()
    ll.add(Node(20))
    return ll.sum()
    Result:20
  3. Code:
    ll = LinkedList()
    return ll.sum()
    Result:0
  4. Code:
    ll = LinkedList()
    ll = LinkedList()
    ll.add(Node(1))
    ll.add(Node(1))
    ll.add(Node(1))
    return ll.sum()
    Result:3
  5. Code:
    ll = LinkedList()
    ll.add(Node(-8))
    ll.add(Node(4))
    ll.add(Node(4))
    return ll.sum()
    Result:0