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.rb111 chars9 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.rb106 chars9 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.rb222 chars16 lines
We can then create a new linked list and add nodes as follows:
main.rb73 chars5 lines
This will create a linked list with nodes containing values 1, 2, and 3 in that order.
gistlibby LogSnag