find the largest node in a linked list in ruby

To find the largest node in a linked list in Ruby, you can iterate through the list and keep track of the current maximum value seen so far. Here's an example implementation:

main.rb
class Node
  attr_accessor :value, :next

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

def find_largest_node(head)
  return nil if head.nil?

  max_node = head
  current_node = head.next

  while current_node
    max_node = current_node if current_node.value > max_node.value
    current_node = current_node.next
  end

  max_node
end
360 chars
23 lines

In this implementation, we define a Node class to represent each node in the linked list. The find_largest_node method takes in the head of the linked list as an argument and returns the largest node in the list.

We initialize max_node to be the head of the list, and current_node to be the next node after head. We iterate through the list and update max_node to be the current node if its value is greater than the current maximum value. Finally, we return max_node.

You can test the algorithm with the following code:

main.rb
node1 = Node.new(1)
node2 = Node.new(5)
node3 = Node.new(9)
node4 = Node.new(3)

node1.next = node2
node2.next = node3
node3.next = node4

largest_node = find_largest_node(node1)
puts largest_node.value # Output: 9
215 chars
12 lines

gistlibby LogSnag