Sum All Elements in a Linked List

tags: addition-accumulator

Till the end of the linked list is reached, add all the values of nodes and return the sum.

Iterative Implementation

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def add(node)
  sum = 0
  current = node
  
  while current
    sum = sum + current.value
    current = current.next
  end
  
  return sum
end

The current pointer begins from the first node and keeps moving one node at a time as the sum gets updated.

Recursive Implementation

The input to the recursive call takes care of traversing the linked list. The return value is the sum of all the nodes.

1
2
3
4
5
6
7
def add(node)
  if node.nil?
    return 0
  end
  
  return node.data + add(node.next)
end

The base case is reached when the end of the linked list in encountered.