简体   繁体   English

使用Java合并排序链接列表

[英]merge sort linked list using java

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;

}

It is throwing stack overflow error. 它引发堆栈溢出错误。 Please help me in correcting my solution I am first dividing my linked list into two halves and then sending them recursively after that i am combining my two sorted linked lists. 请帮助我更正我的解决方案。我先将链表分成两半,然后在将两个排序后的链表合并后递归发送。 the error is showing when I am calling my first list recursively 当我递归调用我的第一个列表时显示错误

if you have a list with 2 elements its expected to keep call the method recursivly: 如果您有一个包含2个元素的列表,则预期它会递归调用该方法:

   while (temp2 != null && temp2.next != null) {
        temp1 = temp1.next;
        temp2 = temp2.next.next;
        count++;
    }

count will equal "1" 计数将等于“ 1”

   Node<Integer> list1 = head;
    Node<Integer> listTemp1 = list1;
    while (count > 0) {
        listTemp1 = listTemp1.next;
        count--;
    }

listTemp1 will be pointing at the second node listTemp1将指向第二个节点

   Node<Integer> list2 = listTemp1.next;
    listTemp1.next = null;
    mergeSort(list1);
    mergeSort(list2);

so from what i see list1 will keep pointing at the first node and list2 will keep pointing at null, note that listTemp1.nex = null does nothing actually as its already pointing to null 所以从我所看到的列表1将继续指向第一个节点,列表2将一直指向null,请注意listTemp1.nex = null实际上并没有执行任何操作,因为它已经指向null

You can solve this simple by decrementing count. 您可以通过减少计数来解决这个简单的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM