I've made a Ruby linked list data structure class and a lookup
method. I know that lookup
will only fetch the first occurrence and I'm ok with that.
Is it a bad implementation? Why is it bad? What can I improve to make it more idiomatic?
# linear collection of data elements, in which linear order is not given by
# their physical placement in memory. Instead, each element points to the next.
class LinkedList
attr_accessor :value, :next
def lookup(lookup_value)
return self if value.eql? lookup_value
return self.next.lookup(lookup_value) unless self.next.nil?
end
end
Test code
root = LinkedList.new
root.value = 5
node1 = LinkedList.new
node1.value = 10
node2 = LinkedList.new
node2.value = 15
node3 = LinkedList.new
node3.value = 12
root.next = node1
node1.next = node2
node2.next = node3
p root.lookup(2) # nil
p root.lookup(15) # #<LinkedList:0x007f83db0a95b8 @value=15, @next=#<LinkedList:0x007f83db0a9590 @value=12>>
p root.lookup(12) # #<LinkedList:0x007fcbe91196a0 @value=12>
node.addNew(value)
and create some sort of constructor maybe following the pattern used byHash[]
, i..eroot = LinkedList[values, ...]
\$\endgroup\$