public class Solution {
public static LinkedListNode<Integer> mergeSort(LinkedListNode<Integer> head) {
//Your code goes
LinkedListNode slow=head, fast=head, temp=head;
while(fast!=null && fast.next!=null){
temp=slow;
fast=fast.next.next;
slow=slow.next;
}
temp.next=null;
LinkedListNode left_side=mergeSort(head);
LinkedListNode right_side=mergeSort(slow);
return merge(left_side, right_side);
}
public static LinkedListNode merge(LinkedListNode<Integer> head1, LinkedListNode<Integer> head2){
LinkedListNode temp_node=new LinkedListNode(0);
LinkedListNode current_node= temp_node;
while(head1!=null && head2!=null){
if(head1.data<=head2.data){
current_node.next=head1;
head1=head1.next;
}else{
current_node.next=head2;
head2=head2.next;
}
current_node=current_node.next;
}
if(head1!=null){
current_node.next=head1;
head1=head1.next;
}
if(head2!=null){
current_node=head2;
head2=head2.next;
}
return temp_node.next;
}
}
我期待一个排序列表,但我得到了一个StackOverflowError
。
我该怎么改正呢?错误是专门针对我在链表左侧调用mergSort
的那一行显示的,我该怎么办呢?
2条答案
按热度按时间cbjzeqam1#
您正在mergeSort()方法中使用递归,并且mergeSort函数没有退出条件。在调用递归之前,您应该有一个退出条件。否则,它将继续调用相同的方法,直到堆栈满为止。因此,堆栈溢出错误。
j91ykkif2#
thumbs已经回答了这个问题。如果你感兴趣,这里有自底向上和自顶向下合并排序单链表的例子。自底向上比较快,快多少取决于节点的数量和节点是否分散(缓存未命中)。将列表复制到一个数组中,排序数组,然后从数组创建一个新的排序列表更快。两个例子的合并函数是相同的:执行if(true){head ...}... while(true){dest ...}以避免使用虚节点(这避免了在每次调用合并时分配和释放虚节点)。
自下而上
自上而下