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

One way of finding the sum of all nodes in a linked list is by traversing the list and adding up the value of each node. Here's an implementation in Ruby:

main.rb
class Node
  attr_accessor :value, :next_node

  def initialize(value, next_node=nil)
    @value = value
    @next_node = next_node
  end
end

class LinkedList
  attr_accessor :head

  def initialize
    @head = nil
  end

  def add(value)
    if @head.nil?
      @head = Node.new(value)
    else
      current = @head
      while current.next_node != nil
        current = current.next_node
      end
      current.next_node = Node.new(value)
    end
  end

  def sum
    current = @head
    sum = 0
    while current != nil
      sum += current.value
      current = current.next_node
    end
    sum
  end
end
613 chars
39 lines

The add method adds a new node to the end of the linked list. The sum method traverses the list, adding up the value of each node and returns the total sum.

Alternatively, we can implement the sum method using recursion:

main.rb
class LinkedList
  attr_accessor :head

  def initialize
    @head = nil
  end

  # add method same as above

  def sum(current=@head)
    return 0 if current.nil?
    current.value + sum(current.next_node)
  end
end
217 chars
15 lines

In this implementation, the sum method takes the current node as an argument, and uses recursion to add up the value of the current node to the sum of the rest of the list (starting from the next node). When the current node is nil, we return 0 to stop the recursion.

gistlibby LogSnag