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

Here is a code snippet to find the average of all nodes in a linked list in Ruby:

main.rb
# Define the Node class for a linked list
class Node
  attr_accessor :value, :next

  def initialize(value)
    @value = value
    @next = nil
  end
end

# Define the LinkedList class
class LinkedList
  attr_accessor :head

  def initialize(head)
    @head = head
  end

  def add_node(value)
    node = Node.new(value)
    current_node = @head
    while current_node.next != nil
      current_node = current_node.next
    end
    current_node.next = node
  end

  def find_average
    current_node = @head
    sum = 0
    count = 0
    while current_node != nil
      sum += current_node.value
      count += 1
      current_node = current_node.next
    end
    sum.to_f / count
  end
end

# Example usage
list = LinkedList.new(Node.new(1))
list.add_node(2)
list.add_node(3)
list.add_node(4)
list.add_node(5)

puts list.find_average # Output: 3.0
848 chars
49 lines

In this code, we define a Node class to represent each node in the linked list, and a LinkedList class to represent the linked list itself. The find_average method of the LinkedList class iterates through all nodes, adding their values to a sum variable and incrementing a count variable to keep track of how many nodes have been visited. Finally, it returns the average by dividing the sum by the count, casting one of the operands to a Float to get a floating-point result.

gistlibby LogSnag