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

One way to find the mode of all nodes in a linked list in Ruby is to iterate through the list and count the occurrences of each node's value using a hash. The mode(s) can then be determined by finding the key(s) with the highest value in the hash.

Here is an example implementation:

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

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

# Define the linked list class
class LinkedList
  attr_accessor :head

  def initialize
    @head = nil
  end

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

  def mode
    count = {}
    max_count = 0
    modes = []

    # Count occurrences of each value in the list
    current = @head
    while current != nil
      if count.has_key?(current.data)
        count[current.data] += 1
      else
        count[current.data] = 1
      end
      max_count = count[current.data] if count[current.data] > max_count
      current = current.next
    end

    # Determine the mode(s)
    count.each do |key, value|
      modes << key if value == max_count
    end

    return modes
  end
end

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

modes = list.mode
puts "Mode(s): #{modes.join(', ')}" # Output: Mode(s): 3
1221 chars
68 lines

gistlibby LogSnag