How to create a Linked List in ruby

Prateek vyas
2 min readJan 21, 2022

--

Hi this is the part 2 of Linked list creation in ruby

Linked List implementation 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

  1. Create a node by passing value and nil to it.
  2. Again create a node the same way.
  3. Now after creating the second node you need to check if the head already exists for the linked list or not?
  4. 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, :nex
def initialize(value, nex)
@value = value
@nex = nex
end
end
# linked list class to attach the nodes while creating
class LinkedList
attr_accessor :head
def 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
end
linked_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! 😄

--

--

Prateek vyas
Prateek vyas

Written by Prateek vyas

Hello i am prateek vyas working as a ruby developer

No responses yet