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.next==null){
return head;
}
// 找到一个轴 使得左边都小于他 右边都大于他 这样的话就排序完成了 然后在左边同样的操作 右边同样的操作
// 先找中点
ListNode slow=head;
ListNode fast=head.next;
while(fast!=null && fast.next!=null){
slow=slow.next;
fast=fast.next.next;
}
ListNode right=slow.next;
slow.next=null;
ListNode rlist=sortInList(right);
ListNode llist=sortInList(head);
return merge(rlist,llist);
}
public ListNode merge (ListNode pHead1, ListNode pHead2) {
// write code here
ListNode dot=new ListNode(0);
ListNode head=dot;
while(pHead1!=null&& pHead2!=null){
if(pHead1.val>=pHead2.val){
head.next=pHead2;
pHead2=pHead2.next;
}else{
head.next=pHead1;
pHead1=pHead1.next;
}
head=head.next;
}
if(pHead1 !=null){
head.next=pHead1;
}
if(pHead2 !=null){
head.next=pHead2;
}
return dot.next;
}
}