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

To add a node to the end of a singly linked list in Ruby, we need to perform the following steps:

  1. Create a new node, let's call it new_node.
  2. Check if the linked list is empty. If it is empty, add the new_node as the head of the linked list.
  3. If the linked list is not empty, traverse the linked list until we reach the last node.
  4. Set the next pointer of the last node to the new_node.

Here's the code for adding a node to the end of a linked list:

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

class LinkedList
  attr_accessor :head
  
  def initialize
    @head = nil
  end
  
  def add_node(data)
    new_node = Node.new(data)
    
    if @head.nil?
      # If the linked list is empty, add the new node as the head
      @head = new_node
    else
      current = @head
      # Traverse the linked list until we reach the last node
      while current.next != nil
        current = current.next
      end
      
      # Set the next pointer of the last node to the new node
      current.next = new_node
    end
  end
end
640 chars
35 lines

With this code, we can create a new linked list and add nodes to the end of it:

main.rb
list = LinkedList.new
list.add_node(1)
list.add_node(2)
list.add_node(3)
# The linked list now contains 1 -> 2 -> 3
116 chars
6 lines

gistlibby LogSnag