简体   繁体   中英

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:

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

count will equal "1"

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

listTemp1 will be pointing at the second node

   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

You can solve this simple by decrementing count.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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