148 Sorted List

Merge Sort O(logN) space

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode sortList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode fast = head;
        ListNode slow = head;
        ListNode prevEnd = null;
        while(fast != null && fast.next != null){
            prevEnd = slow;
            fast = fast.next.next;
            slow = slow.next;
        }
        prevEnd.next = null;
        ListNode l1 = sortList(head);
        ListNode l2 = sortList(slow);
        return merge(l1, l2);
    }

    public ListNode merge(ListNode l1, ListNode l2){
        ListNode preHead = new ListNode(-1);
        ListNode current = preHead;
        while(l1 != null && l2 != null){
            if( l1.val < l2.val ){
                current.next = l1; 
                l1 = l1.next;
            }
            else{
                current.next = l2;
                l2 = l2.next;
            }
            current = current.next;
        }
        if(l1 != null){
            current.next = l1;
        }

        if(l2 != null){
            current.next = l2;
        }
        return preHead.next;
    }

}

results matching ""

    No results matching ""