简体   繁体   中英

Sort Link List using Merge Sort in Java

I am trying to implement a merge sort on Linkedin List . Its resulting into a StackOverflowError error . Following is the implementation done by me . Kindly tell me the alterations to be done.

public class Solution {
    public ListNode sortList(ListNode A) {
        if (A == null || A.next == null)
        {
            return A;
        }
        ListNode middle = getMiddle(A);
        ListNode middleNext = middle.next;
        middle.next = null;
        ListNode left = sortList(A);
        ListNode right = sortList(middleNext);
        ListNode head = combine(left,right);
        return head;
    }

    public ListNode combine(ListNode head,ListNode otherHead){
        ListNode combineResult = null;
        if(head==null)
            return otherHead;
        if(otherHead == null)
            return head;
        if(head.val<=otherHead.val){
            combineResult = head;
            combineResult.next = combine(head.next,otherHead);
        } else {
            combineResult = otherHead;
            combineResult.next = combine(head,otherHead.next);
        }
        return combineResult;
    }

    public ListNode getMiddle(ListNode A){
        ListNode fastPtr = A;
        ListNode slowPtr = A;
        while(fastPtr!=null && fastPtr.next!=null){
            fastPtr = fastPtr.next.next;
            slowPtr = slowPtr.next;
        }
        return slowPtr;
    }
}

You have this method declaration

public ListNode sortList(ListNode A) {

and without any change to A , you call the method like this:

ListNode left = sortList(A);

Since you have no end sign, you have infinite recursivity. The input of sortList should be the leftmost and the rightmost node of your current interval, and, since you have a linked list, the number of items in the interval would not hurt either as a parameter, to avoid having to calculate it repeatedly. Now, instead of this, you have a single parameter, a ListNode called A . That's not enough to define an interval.

The idea of merge sort is to repeatedly dividing an ordered set into halves, partitioning it, posing similar, but easier subproblems until we reach triviality and solve the trivial tasks, then the combination of such trivial tasks becomes easier.

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