我的排序链表的代码如下:
def sort_list(head)
return head if head.nil? || head.next.nil?
mid_node = find_mid(head)
second_half = mid_node.next
mid_node.next = nil
left_half = sort_list(head)
right_half = sort_list(second_half)
merge(left_half, right_half)
end
def merge(left_head, right_head)
left = left_head
right = right_head
dummy_head = dummy = ListNode.new(-1)
until left.nil? || right.nil?
if left.val > right.val
dummy.next = right
right = right.next
else
dummy.next = left
left = left.next
end
dummy = dummy.next
end
#here there may be one list left over.
dummy.next = left unless left.nil?
dummy.next = right unless right.nil?
dummy_head.next
end
def find_mid(head)
return nil if head.nil?
slow_ptr = fast_ptr = head
until fast_ptr.nil? || fast_ptr.next.nil?
fast_ptr = fast_ptr.next.next
slow_ptr = slow_ptr.next
end
slow_ptr
end
这给了我一个太深的错误,我不知道为什么。好像我正确地终止了这两个功能。 sort_list逻辑对我来说很好,我测试了find_mid函数。合并对我来说也很好......那么这里有什么?
答案 0 :(得分:2)
问题在于您的find_mid
功能。如果使用仅包含两个节点的链表测试它,您会看到它返回最后一个节点而不是第一个节点。
示例:
list = ListNode.new(4, ListNode.new(3))
res = find_mid(list)
puts res.val # It would print 3
因此,列表不再缩小,代码将使用大小为2 永远的链接列表重复递归,或实际上,直到堆栈太深错误< /强>
然后解决方案是按如下方式更改功能:
def find_mid(head)
return nil if head.nil?
slow_ptr = head
fast_ptr = head.next
until fast_ptr.nil? || fast_ptr.next.nil?
fast_ptr = fast_ptr.next.next
slow_ptr = slow_ptr.next
end
slow_ptr
end