find the smallest node in a linked list in ruby

To find the smallest node in a linked list, you can iterate over the list and compare the value of each node to find the minimum. Here's an implementation in Ruby:

main.rb
class Node
  attr_accessor :value, :next

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

class LinkedList
  attr_accessor :head

  def initialize()
    @head = nil
  end

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

  def find_smallest_node()
    return nil if @head.nil?
    current = @head
    min = current.value
    while current.next != nil
      current = current.next
      min = current.value if current.value < min
    end
    return min
  end
end
661 chars
40 lines

Here, we first define two classes, Node and LinkedList. Node represents a single node in the linked list, which stores a value and a pointer to the next node in the list. LinkedList represents the entire linked list, which stores a reference to the head node.

We define a find_smallest_node method that iterates over the linked list and returns the value of the smallest node. We initialize the minimum to be the value of the head node, and then update it whenever we encounter a smaller node during the iteration.

To use this code, you can create a new linked list and add nodes to it using the add_node method. Then, you can call the find_smallest_node method to get the value of the smallest node. For example:

main.rb
list = LinkedList.new()
list.add_node(5)
list.add_node(3)
list.add_node(8)
list.add_node(1)

puts list.find_smallest_node() # outputs 1
136 chars
8 lines

gistlibby LogSnag