March 09, 2019

148. Sort List

148. Sort List

/**
 * 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 pre = head;
        ListNode slow = head;
        ListNode fast = head;
        
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode l1 = pre;
        ListNode l2 = slow.next;
        slow.next = null;
        
        l1 = sortList(l1);
        l2 = sortList(l2);
        return mergeTwoLists(l1, l2);
    }
    
    private ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode l = new ListNode(0);
        ListNode dummy = l;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                l.next = new ListNode(l1.val);
                l = l.next;
                l1 = l1.next;
            } else {
                l.next = new ListNode(l2.val);
                l = l.next;
                l2 = l2.next;                
            }
        }
        while (l1 != null) {
            l.next = new ListNode(l1.val);
            l = l.next;
            l1 = l1.next;
        } 
        while (l2 != null) {
            l.next = new ListNode(l2.val);
            l = l.next;
            l2 = l2.next;               
        }
        return dummy.next;
    }
}
comments powered by Disqus