Andrew Andrew - 6 months ago 9
Ruby Question

Implementing a LinkedList in Ruby

I'm trying to implement a singly linked LinkedList in Ruby and I'm having some trouble trying to figure out why some of the nodes are disappearing. Here's what I have so far:

class Node
attr_accessor :data, :next
def initialize(data)
@data = data
end
end

class LinkedList
attr_accessor :head

def insert(data)
node = Node.new(data)
if @head.nil?
@head = node
else
travel = @head
unless travel.next.nil?
travel = travel.next
end
travel.next = node
end
print @head
end

def to_string
result = ""
travel = @head
unless travel.nil?
result << "#{travel.data} => "
travel = travel.next
end
result << "END"
result
end

end


And here is a call to this class:

list = LinkedList.new
list.insert(5)
list.insert(6)
list.insert(7)


At the end of insert, I print out
@head
and I can see that all three nodes are in the list. However, when I make a separate call to
to_string
,
@head
only has the first node but everything else is gone. Can anyone point me in the right direction to what's wrong?

Thanks!

Answer

There is a problem with the keyword unless. In ruby, it is a conditional statement, just like if. It is not a loop. Just replace them with the keyword until.

About the linked list in general, the point of it is to make insertion in O(1), whereas you are doing it in O(n) (traverse the list and insert the node at the end). Instead, you can just insert the new node at the beginning, it will be ok.

Finally, ruby's convention is to name the to_string method to_s, so it will be called when printing the list.

Also, you have the possibility of making Node an internal class of LinkedList. It will be useful if you want to implement other node-based data structures (deque, ring, tree, etc)

Comments