My c# solution


  • 0
    S
    public class Solution {
        public ListNode SortList(ListNode head) 
        {
            if(head == null || head.next == null)
                return head;
            var slow = head;
            var fast = head;
            while(fast.next != null && fast.next.next != null)
            {
                slow = slow.next;
                fast = fast.next.next;
            }
            var h1 = head;
            var h2 = slow.next;
            slow.next = null;
            h1 = SortList(h1);
            h2 = SortList(h2);
            return Merge(h1, h2);
        }
        
        
        
        private ListNode Merge(ListNode h1, ListNode h2)
        {
            var dummy = new ListNode(0);
            var pre = dummy;
            while(h1 != null && h2 != null)
            {
                if(h1.val < h2.val)
                {
                    pre.next = h1;
                    h1 = h1.next;
                }
                else
                {
                    pre.next = h2;
                    h2 = h2.next;
                }
                pre = pre.next;
            }
            if(h1 != null)
            {
                pre.next = h1;
            }
            else
            {
                pre.next = h2;
            }
            return dummy.next;
        }
    }
    

Log in to reply
 

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