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

To find the range of all nodes in a linked list in Ruby, you can iterate through the nodes and keep track of the minimum and maximum values. Here's an example implementation:

main.rb
class Node
  attr_accessor :value, :next_node
  
  def initialize(value, next_node = nil)
    @value = value
    @next_node = next_node
  end
end

def linked_list_range(head)
  # Initialize min and max with the value of the first node
  min = head.value
  max = head.value
  
  # Iterate through the rest of the nodes and update min and max if necessary
  current_node = head.next_node
  while current_node != nil
    min = [min, current_node.value].min
    max = [max, current_node.value].max
    current_node = current_node.next_node
  end
  
  # Return the range as a tuple
  return [min, max]
end
601 chars
26 lines

Here's an example usage of the function:

main.rb
# Create a linked list with some values
node3 = Node.new(8, nil)
node2 = Node.new(3, node3)
node1 = Node.new(1, node2)

# Find the range of the linked list
range = linked_list_range(node1)
puts "Range: #{range}"  # Output: Range: [1, 8]
237 chars
9 lines

gistlibby LogSnag