import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
// 给链表排序 !
// 采用归并的思想,合并有序链表!
public ListNode sortInList (ListNode head) {
// write code here
if(head == null) return null;
// 将链表一分为二
ListNode mid = getMid(head);
if(mid == null) return head;
return merageSort(sortInList(head),sortInList(mid));
}
// 获取链表的中间节点!
private ListNode getMid(ListNode head){
if(head == null) return null;
ListNode fake_head = new ListNode(-1);
fake_head.next = head;
ListNode pre = fake_head;
ListNode slow = head,fast = head;
while(fast != null){
pre = pre.next;
fast = fast.next;
slow = slow.next;
if(fast != null) fast = fast.next;
}
pre.next = null;
return slow;
}
// 合并两个有序链表
private ListNode merageSort(ListNode l1,ListNode l2 ){
if(l1 == null) return l2;
if(l2 == null) return l1;
if(l1.val < l2.val){
l1.next = merageSort(l1.next,l2);
return l1;
}
l2.next = merageSort(l1,l2.next);
return l2;
}
}