我曾经使用python来做,我不知道如何通过Crystal定义ListNode类,我的工作只是针对Leetcode网站中的第二个问题,即加两个数字。我已经尝试过这种方式,但是对于ListNode错误消息却得到了未定义的方法“下一个”
class ListNode
def initialize(x : Int32)
@val = x
@next = Nil
end
end
def addTwoNumbers(l1 : ListNode, l2 : ListNode)
divide_value = 0
first = l1
second = l2
is2 = 0
while True
sum = l1.val + l2.val + divide_value
residual_value = sum % 10
l1.val = residual_value
l2.val = residual_value
divide_value = sum / 10
if l1.next and l2.next
l1 = l1.next
l2 = l2.next
elsif !l1.next and l2.next
l1.val = 0
l2 = l2.next
is2 = 1
elsif l1.next and !l2.next
l2.val = 0
l1 = l1.next
else
if is2
if divide_value != 0
l2.next = ListNode.new divide_value
return second
end
return second
else
if divide_value != 0
l1.next = ListNode.new divide_value
return first
end
return first
end
end
end
end
l1 = ListNode.new 1
l2 = ListNode.new 9
l2 = l2.next
l2 = ListNode.new 9
result = addTwoNumbers(l1,l2)
while result
puts(result.val)
result = result.next
end
有人可以帮助我吗?
答案 0 :(得分:3)
您需要为实例变量创建getter和setter方法,以便访问它们。
https://crystal-lang.org/reference/syntax_and_semantics/methods_and_instance_variables.html
在您的代码中,只需添加property
:
class ListNode
property val
property next_node # avoiding `next`. It is a reserved keyword.
def initialize(x : Int32)
@val = x
@next_node = Nil
end
end
l2 = ListNode.new 9
l2 = l2.next_node # ok now