最近本人在刷 LeetCode,所选的语言是 ruby,刷到 86 题 partition list。
小弟代码如下:
def append_list(head, tail, node, vars)
if head.nil?
eval "head = node", vars
eval "tail = node", vars
# head, tail = node, node
else
eval "tail.next = node", vars
eval "tail = node", vars
# tail.next = node
# tail = node
end
end
def partition(head, x)
return head if head.nil? || head.next.nil?
left, right = nil, nil
while head && head.val < x
node = head
head = head.next
node.next = nil
append_list(left, right, node, binding)
end
if head
p = head
while p.next
if p.next.val < x
node = p.next
p.next = node.next
node.next = nil
append_list(left, right, node, binding)
else
p = p.next
end
end
end
append_list(left, right, node, binding)
left
end
主要是 append_list 方法,因为 ruby 中参数传递的是拷贝,不是引用,所以查了下需要用 binding,但是小弟改了代码,使用了 eval 的形式,但是运行时却死循环了,所以想请教下各位大佬,哪里写错了。