/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
if (head==null||head.next==null) return head;
// ListNode head = head;
ListNode mid = head;
ListNode end = head;
int c = 1;
while(end.next != null){
if((c&1) == 0){
mid = mid.next;
}
end = end.next;
c++;
}
ListNode midNext = mid.next;
mid.next = null;
end.next = null;
ListNode list1 = sortList(head);
ListNode list2 = sortList(midNext);
return combak(list1,list2);
}
public ListNode combak(ListNode lh,ListNode rh){
ListNode newH = new ListNode(-1);
ListNode n = newH;
while(lh != null && rh != null){
if(lh.val < rh.val){
newH.next = lh;
lh = lh.next;
newH = newH.next;
}else{
newH.next = rh;
rh = rh.next;
newH = newH.next;
}
}
if(lh != null){
newH.next = lh;
}
if(rh != null){
newH.next = rh;
}
return n.next;
}
}