我找不到代码有什么问题,但是当我提交它时,有两个测试用例会产生运行时错误。请帮我弄清楚那个错误。我已经检查了至少30个自定义测试用例,但它为所有测试用例提供了正确的输出。
Code
public static Node mergeTwoList(Node head1, Node head2) {
Node c = null;
if (head1 == null) {
return head2;
} else if (head2 == null) {
return head1;
}
if (head1.data < head2.data) {
c = head1;
c.next = mergeTwoList(head1.next, head2);
} else {
c = head2;
c.next = mergeTwoList(head1, head2.next);
}
return c;
}
如果有人弄明白,请告诉我。
答案 0 :(得分:1)
我认为原因是stackoverflow,因为你使用递归,递归会产生堆栈,如果链表很长,可能会导致堆栈溢出。
在leecode上有一个类似的问题,我用迭代来解决它, 我将解决方案粘贴到我的博客中,虽然解释是在Madarin中,但代码仍然可以作为参考。链接如下: http://codecrazer.blogspot.tw/2017/07/leetcode-21-merge-two-sorted-lists.html