2017-07-28 58 views
1

我无法找到任何代码错误,但是当我提交它时,两个测试用例给运行时错误。请帮我弄清楚这个错误。我已经检查了至少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

什么是错误? –

+0

在线工具没有提供具体的细节。它只是显示运行时错误 –

+0

@KillerDeath可能是由于递归导致的堆栈溢出。你找到了什么? –

回答

1

我认为原因是stackoverflow,因为你使用递归,并递归会产生堆栈,如果linklist很长,它可能会导致stackoverflow。

有一个关于leecode的类似问题,我用迭代的方法解决它, 我把解决方案粘贴到我的博客中,尽管解释是在Madarin中,代码仍然可以作为参考。链接提供如下: http://codecrazer.blogspot.tw/2017/07/leetcode-21-merge-two-sorted-lists.html