hey, im pretty new to ruby and im having trouble. this is not my
original code (much longer), but i quickly rewrote the part of the
data structure that was creating the problem so i could post it here:
i have a node class that is used to make a linked list. the node
object has a value, a pointer to the next node in the list, and
another node that is sometimes used to point to another node in the
list somewhere.
when pointer2 is not used it is set to nil. However when i try to
print out my linked list (which will print each node’s values and
where its pointers are pointing) it crashes when it reaches a pointer
set to nil.
i tried making an if-then-else check, but it doesnt seem to work. can
anyone help me? thanks in advance.
class Node
def initialize(v,p1,p2)
@value = v
@pointer1 = p1 #next node
@pointer2 = p2 #points to another node
end
def getP1
@pointer1
end
def setP1(x)
@pointer1 = x
end
def getP2
@pointer2
end
def setP2(x)
@pointer2 = x
end
def getV
@value
end
def setV(x)
@value = x
end
end
### code starts here ###
c1 = Node.new(1,nil,nil)
c2 = Node.new(2,nil,nil)
c3 = Node.new(3,nil,nil)
c1.setP1(c2)
c1.setP2(c2)
c2.setP1(c3)
current = c1
while current.getP1 != nil
print "value = #{current.getV}, pointer1 = #{current.getP1.getV},
"
if current.getP2.getV != nil then print "pointer2 =
#{current.getP2.getV}\n" else print "null\n" end
current = current.getP1
end
output:
$ ruby node.rb
value = 1, pointer1 = 2, pointer2 = 2
node.rb:49: undefined method `getV’ for nil:NilClass (NoMethodError)
value = 2, pointer1 = 3,
$