1
我的代碼如下:排序排序鏈表鏈表問題
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函數。 Merge對我來說也很好......所以這裏有什麼?
@Sunny高興它爲你工作 – Aegis