create a linked list in ruby

To create a linked list in Ruby, we need to define two classes: Node and LinkedList.

The Node class defines the individual elements of the linked list, called nodes. Each node has two properties, value which contains the actual value of the node and next which contains a pointer to the next node in the list.

main.rb
class Node
  attr_accessor :value, :next

  def initialize(value)
    @value = value
    @next = nil
  end
end
111 chars
9 lines

The LinkedList class is responsible for maintaining the nodes in the list. It has two properties, head which points to the first node in the list, and tail which points to the last node in the list.

main.rb
class LinkedList
  attr_accessor :head, :tail

  def initialize
    @head = nil
    @tail = nil
  end
end
106 chars
9 lines

To add a node to the list, we first create a new node using the Node class and set the value. If the list is empty, we set the new node to be the head and the tail. Otherwise, we set the next property of the previous tail to point to the new node, and then set the new node as the tail.

main.rb
class LinkedList
  # ...

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

    if @head.nil?
      @head = new_node
      @tail = new_node
    else
      @tail.next = new_node
      @tail = new_node
    end
  end
end
222 chars
16 lines

We can then create a new linked list and add nodes as follows:

main.rb
list = LinkedList.new
list.add_node(1)
list.add_node(2)
list.add_node(3)
73 chars
5 lines

This will create a linked list with nodes containing values 1, 2, and 3 in that order.

gistlibby LogSnag