大致思路:由O(nlog(n))时间复杂度选择归并排序。与常规归并的差异并不大,只需要关注几个细节:1. 通过快慢指针找中间节点 2. 涉及到两个有序链表的合并问题 3. 边界问题,当只有一个节点时,直接返回这个节点
public class Solution {
ListNode min = new ListNode(Integer.MAX_VALUE);
public ListNode sortList (ListNode head) {
if(head==null || head.next==null) return head;
merge(head);
return min;
}
public ListNode merge(ListNode node){
if(node.next==null) return node;
ListNode fast = node,slow = node;
while(fast.next!=null && fast.next.next!=null){
fast = fast.next.next;
slow = slow.next;
}
ListNode node_ = slow.next;
slow.next = null;
node = merge(node);
node_ = merge(node_);
ListNode n_ = new ListNode(1),n = n_;
while(node!=null && node_ != null){
if(node.val<node_.val){
min = node.val<min.val?node:min;
n.next = node;
node = node.next;
n = n.next;
}else{
min = node_.val<min.val?node_:min;
n.next = node_;
node_ = node_.next;
n = n.next;
}
}
if(node!=null) n.next = node;
if(node_!=null) n.next = node_;
return n_.next;
}
}