C# merge sort AC solution


  • 0
    J
    public ListNode SortList(ListNode head)
        {
            int length = 0; ListNode node = head;
            while (node != null) { length++; node = node.next; }
            if (length == 0) { return head; }
            int i = 1; ListNode r = head;
            while (i < length) { r = r.next; i++; }
            ListNode newHead = SortList_Impl(head, r, length);
            return newHead;
        }
    
        private ListNode SortList_Impl(ListNode p, ListNode r, int length)
        {
            if (length == 1) { return p; }
            int mIndex = length / 2;
            int i = 1; ListNode m = p;
            while (i < mIndex) { m = m.next; i++; }
            int leftLen = length / 2; int rightLen = length - leftLen;
            ListNode cache = m.next;
            ListNode left = SortList_Impl(p, m, leftLen);
            ListNode right = SortList_Impl(cache, r, rightLen);
            ListNode newHead = null; int lefti = 1; int righti = 1;
            ListNode lastnode = null;
            while (lefti <= leftLen && righti <= rightLen)
            {
                ListNode pickup = null;
                if (left.val <= right.val) { pickup = left; left = left.next; ++lefti; }
                else { pickup = right; right = right.next; ++righti; }
                if (newHead == null) { newHead = pickup; }
                else { lastnode.next = pickup; }
                lastnode = pickup;
            }
    
            ListNode leftover = null; int leftoverLength = 0; int k = 0;
            if (lefti <= leftLen) { leftover = left; leftoverLength = leftLen; k = lefti; }
            else { leftover = right; leftoverLength = rightLen; k = righti; }
            while (k <= leftoverLength)
            {
                if (newHead == null) { newHead = leftover; }
                else { lastnode.next = leftover; }
                lastnode = leftover;
                leftover = leftover.next; ++k;
            }
            lastnode.next = null;
            return newHead;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.