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

    self.next = 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 = current.next


    return sum


# Test the LinkedList class

node1 = Node(1)

node2 = Node(2)

node3 = Node(3)

node4 = Node(4)


node1.next = node2

node2.next = node3

node3.next = 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

0 Comments