class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode mid = getMid(head);
ListNode second = mid.next;
mid.next = null;
ListNode left = sortList(head);
ListNode right = sortList(second);
return mergeSort(left, right);
}
public static ListNode mergeSort(ListNode left, ListNode right) {
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
while (left != null && right != null) {
if (left.val <= right.val) {
tail.next = left;
left = left.next;
} else {
tail.next = right;
right = right.next;
}
tail = tail.next;
}
if (left != null) {
tail.next = left;
} else {
tail.next = right;
}
return dummy.next;
}
public static ListNode getMid(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode slow = head;
ListNode fast = head.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}
class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode slow = head;
ListNode fast = head.next;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
ListNode second = slow.next;
slow.next = null;
ListNode left = sortList(head);
ListNode right = sortList(second);
return mergeSort(left, right);
}
public static ListNode mergeSort(ListNode left, ListNode right) {
ListNode dummy = new ListNode();
ListNode tail = dummy;
while (left != null && right != null) {
if (left.val <= right.val) {
tail.next = left;
tail = tail.next;
left = left.next;
} else {
tail.next = right;
tail = tail.next;
right = right.next;
}
}
tail.next = left == null? right : left;
return dummy.next;
}
}