How to create a Linked List in ruby
2 min readJan 21, 2022
Hi this is the part 2 of Linked list creation in ruby
In the previous post we understood how to create the nodes for a linked list
Now it’s time to join them
Algorithm to implement a linked list in ruby
- Create a node by passing value and nil to it.
- Again create a node the same way.
- Now after creating the second node you need to check if the head already exists for the linked list or not?
- If it exists?(Obviously yes in our case) then point the Next of Head(First node) to Second node.
Let’s see how the code looks like after joining the nodes while creating
Copy and Paste the same in your editor to see the code in action
# Node class to create node
class Node
attr_accessor :value, :nexdef initialize(value, nex)
@value = value
@nex = nex
end
end# linked list class to attach the nodes while creating
class LinkedList
attr_accessor :headdef push(value)
if !head
@head = Node.new(value, nil)
else
last_node = head
while last_node
second_last_node = last_node
last_node = last_node.nex
end
second_last_node.nex = Node.new(value, nil)
end
end
endlinked_list = LinkedList.new
while true
p "enter the node value in the input and we will give you the linked list"
value = gets.chomp
linked_list.push(value)
p linked_list
p "you want to exit?"
if_exit = gets.chomp
if if_exit == 'yes'
break
end
end
p linked_list
Thank you for reading it!
Happy coding! 😄