Sort List
public class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode slow = head, fast = head;
while(fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
fast = slow.next;
slow.next = null;
slow = head;
ListNode first = sortList(slow);
ListNode second = sortList(fast);
return merge(first, second);
}
private ListNode merge(ListNode first, ListNode second) {
ListNode dummy = new ListNode(0);
ListNode head = dummy;
while(first != null && second != null) {
if(first.val < second.val) {
ListNode next = first.next;
head.next = first;
head = head.next;
head.next = null;
first = next;
} else {
ListNode next = second.next;
head.next = second;
head = head.next;
head.next = null;
second = next;
}
}
if(first != null) {
head.next = first;
} else {
head.next = second;
}
return dummy.next;
}
}

浙公网安备 33010602011771号