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
return sort(head, null);
}
private ListNode sort(ListNode head, ListNode tail){
// 递归出口:链表元素个数小于等于1个
if(head == null)return head;
if(head.next == tail){
head.next = null;
return head;
}
// 找到中间节点是关键
ListNode slow = head, fast = head;
while(fast != tail){
slow = slow.next;
fast = fast.next;
if(fast != tail)fast = fast.next;
}
return merge(sort(head, slow), sort(slow, tail));
}
private ListNode merge(ListNode l1, ListNode l2){
ListNode dummy = new ListNode(-1);
ListNode cur = dummy;
while(l1 != null && l2 != null){
if(l1.val < l2.val){
cur.next = l1;
l1 = l1.next;
}else{
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
cur.next = l1 == null ? l2 : l1;
return dummy.next;
}
}
自顶向下的归并排序,时间复杂度可以满足O(nlogn)

京公网安备 11010502036488号