Sum of linked list in python

 Sum of  linked list in python

To find the sum of the elements in a linked list in Python, you can use a loop to iterate through the list and add up the values of the nodes. Here is an example of how you might do this:

# Define a Node class

class Node:

  def __init__(self, value, next=None):

    self.value = value = next

# Define a LinkedList class

class LinkedList:

  def __init__(self, head=None):

    self.head = head

  def sum(self):

    # Initialize the sum to 0

    sum = 0

    # Set the current node to the head

    current = self.head

    # Iterate through the list and add the values of the nodes

    while current:

      sum += current.value

      current =

    return sum

# Test the LinkedList class

node1 = Node(1)

node2 = Node(2)

node3 = Node(3)

node4 = Node(4) = node2 = node3 = node4

linked_list = LinkedList(node1)

print(linked_list.sum())  # Output: 10

This approach works by initializing a sum variable to 0 and setting

Post a Comment