add a node to the beginning of a linked list in ruby

To add a new node to the beginning of a linked list in Ruby, you will need to follow these steps:

  1. Create a new node with the desired value.
  2. Set the "next" pointer of the new node to the current head of the linked list.
  3. Set the head of the linked list to be the new node.

Here is an example code snippet that implements this logic:

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

class LinkedList
  attr_accessor :head
  
  def initialize
    @head = nil
  end
  
  def add_to_front(value)
    new_node = Node.new(value)
    new_node.next_node = @head
    @head = new_node
  end
end
327 chars
23 lines

In this example, we define two classes: Node, which represents a single node in the linked list, and LinkedList, which represents the entire linked list. The add_to_front method of the LinkedList class is what we use to add a new node to the beginning of the list.

To use this code, you can create a new instance of the LinkedList class and then call the add_to_front method with the value you want to add:

main.rb
list = LinkedList.new
list.add_to_front(42)
list.add_to_front(13)
list.add_to_front(8)

puts list.head.value # Output: 8
121 chars
7 lines

In this example, the puts statement will output 8, since that is the value of the first node in the linked list after we have added three nodes with values 8, 13, and 42.

gistlibby LogSnag