import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类 the head node
* @return ListNode类
*/
public ListNode sortInList (ListNode head) {
// write code here
if(head==null||head.next==null){
return head;
}
return sort(head);
}
private ListNode sort(ListNode head) {
// TODO
if(head==null||head.next==null){
return head;
}
ListNode middle = getMiddle(head);
head = sort(head);
middle = sort(middle);
return merge(head,middle);
}
private ListNode merge(ListNode head, ListNode middle) {
// TODO
ListNode res = new ListNode(Integer.MIN_VALUE);
ListNode cur = res;
ListNode cur1 = head;
ListNode cur2 = middle;
while(cur1!=null&&cur2!=null){
if(cur1.val<=cur2.val){
cur.next = cur1;
cur = cur.next;
cur1 = cur1.next;
}else{
cur.next = cur2;
cur = cur.next;
cur2 = cur2.next;
}
}
if(cur1!=null){
cur.next = cur1;
}else{
cur.next = cur2;
}
return res.next;
}
private ListNode getMiddle(ListNode head) {
// TODO
ListNode fast = head.next;
ListNode slow = head;
while(fast!=null&&fast.next!=null){
fast = fast.next.next;
slow = slow.next;
}
ListNode middle = slow.next;
slow.next = null;
return middle;
}
}