find the first node in a linked list in ruby

To find the first node in a linked list in Ruby, you can use the built-in head method of the linked list. Here is an example code snippet:

main.rb
class Node
  attr_accessor :data, :next

  def initialize(data)
    @data = data
  end
end

class LinkedList
  attr_accessor :head

  def initialize
    @head = nil
  end

  def add_node(data)
    new_node = Node.new(data)

    if @head.nil?
      @head = new_node
    else
      current = @head
      while current.next != nil
        current = current.next
      end
      current.next = new_node
    end
  end
end

# create a new linked list
list = LinkedList.new

# add nodes to the list
list.add_node(1)
list.add_node(2)
list.add_node(3)

# find the first node
first_node = list.head
puts first_node.data # output: 1
622 chars
42 lines

In this example, we define a Node class and a LinkedList class. The add_node method is used to add new nodes to the linked list. To find the first node in the linked list, we can simply access the head property of the list. The first node is the one that the head property points to.

related categories

gistlibby LogSnag