这道题目关键是考虑怎么实现O nlogn ,所以要找到中点,迭代,其他和merge sort 2 list 一样
类似题目 merge k sorted list, merge 2 sorted list
参考 http://www.cnblogs.com/springfor/p/3869372.html
public class Solution {
// 问题关键要想到找中点,然后迭代产生O(nlogn)
public ListNode sortList(ListNode head) {
if(head==null || head.next==null) return head;
ListNode left = new ListNode(0);
ListNode right = new ListNode(0);
ListNode run = head;
ListNode wk = head;
while(run.next!=null && run.next.next!=null){
run = run.next.next;
wk= wk.next;
}
ListNode first = head;
ListNode second = wk.next;
wk.next = null; // 干啥的??
// 以下是想不到的,可以先排序一下
if(first!=second){
left = sortList(first);
right = sortList(second);
}
return mergeLists(left, right);
}
public ListNode mergeLists(ListNode left, ListNode right){
if(left==null) return right;
if(right==null) return left;
ListNode h = new ListNode(-1);
ListNode cur = h;
while(left!=null && right !=null){
if(left.val>right.val){
cur.next = right;
cur = cur.next;
right = right.next;
}else{
cur.next = left;
cur = cur.next;
left = left.next;
}
}
if(left!=null) cur.next = left;
if(right!=null) cur.next = right;
return h.next;
}
}