* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
import java.util.*;
public class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode midNode = getMid(head);
ListNode midNext = midNode.next;
midNode.next = null;
return merge(sortList(head), sortList(midNext));
}
private ListNode getMid(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
private ListNode merge(ListNode head1, ListNode head2) {
ListNode dummy = new ListNode(-1);
ListNode curNode = dummy;
while (head1 != null && head2 != null) {
if (head1.val <= head2.val) {
curNode.next = head1;
head1 = head1.next;
} else {
curNode.next = head2;
head2 = head2.next;
}
curNode = curNode.next;
}
curNode.next = head1 == null ? head2 : head1;
return dummy.next;
}
}