【发布时间】:2016-05-22 11:43:53
【问题描述】:
private static void mergeSort(Node<Integer> head) {
if (head==null || head.next == null) {
return;
}
Node<Integer> temp1 = head;
Node<Integer> temp2 = head;
int count = 0;
while (temp2 != null && temp2.next != null) {
temp1 = temp1.next;
temp2 = temp2.next.next;
count++;
}
Node<Integer> list1 = head;
Node<Integer> listTemp1 = list1;
while (count > 0) {
listTemp1 = listTemp1.next;
count--;
}
Node<Integer> list2 = listTemp1.next;
listTemp1.next = null;
mergeSort(list1);
mergeSort(list2);
Node<Integer> finalHead = null;
Node<Integer> finalTail = null;
if (list1.data < list2.data) {
finalHead = list1;
list1 = list1.next;
} else {
finalHead = list2;
list2 = list2.next;
}
finalTail = finalHead;
while (list1 != null && list2 != null) {
if (list1.data < list2.data) {
finalTail.next = list1;
finalTail = list1;
list1 = list1.next;
} else {
finalTail.next = list2;
finalTail = list2;
list2 = list2.next;
}
}
if (list1 == null) {
finalTail.next = list2;
} else if (list2 == null) {
finalTail.next = list1;
}
return;
}
抛出堆栈溢出错误。请帮助我纠正我的解决方案 我首先将我的链表分成两半,然后递归发送它们 之后,我将我的两个排序链表组合起来。 当我递归调用我的第一个列表时显示错误
【问题讨论】:
-
提示:不要在一种方法中做所有事情:将功能分成几个方法并单独测试每个方法。堆栈溢出错误很可能意味着:您的递归没有停止。
标签: java linked-list mergesort