find the sum of all nodes in a linked list in python

To find the sum of all nodes in a linked list using Python, we can define a function that iterates through the nodes and accumulates the sum of their values. Here's an example implementation:

main.py
class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

def sum_nodes(head):
    """
    This function takes the head of a linked list as input and returns the sum
    of all nodes in the list.
    """
    current = head
    total = 0
    while current:
        total += current.value
        current = current.next
    return total
373 chars
17 lines

Here, we define a Node class that represents each individual node in the linked list. The value attribute holds the value of the node, and the next attribute points to the next node in the list.

The sum_nodes function takes the head of the linked list as input and initializes a current variable to the head. We also initialize a total variable to 0, which will accumulate the sum of all nodes.

We then enter a loop that iterates over the nodes in the list. Inside the loop, we add the value of the current node to the total, and update current to point to the next node in the list.

Finally, we return the total when the loop is finished, which gives us the sum of all nodes in the linked list.

related categories

gistlibby LogSnag