Sum of linked list in python
# 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
0 Comments
if you are not getting it then ask i am glad to help