find the length of a linked list in ruby

To find the length of a linked list in Ruby, we can use the count method. count returns the number of elements in an enumerable object.

Assuming our linked list is represented by a Node class and we have a variable head that points to the first node of the list, we can find the length like this:

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

# create a linked list with 3 nodes
node3 = Node.new("3")
node2 = Node.new("2", node3)
node1 = Node.new("1", node2)
head = node1

# count the number of nodes in the list
length = head ? head.count : 0

puts length  # output: 3
374 chars
20 lines

In the code above, we create a linked list with 3 nodes and point head to the first node. We then use the count method to find the number of nodes in the list. If head is nil, we return 0 (i.e. an empty list).

gistlibby LogSnag