在 O(n log n) 時間複雜度和常數級空間複雜度下,對鏈表進行排序。bash
示例 1:ui
輸入: 4->2->1->3
輸出: 1->2->3->4
複製代碼
示例 2:spa
輸入: -1->5->3->4->0
輸出: -1->0->3->4->5
複製代碼
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
if( head == null || head.next == null ){
return head;
}
ListNode slow = head , fast = head , pre = head;
while( fast != null && fast.next != null ){
pre = slow;
slow = slow.next;
fast = fast.next.next;
}
pre.next = null;
return merge( sortList( head ) , sortList( slow ) );
}
public ListNode merge( ListNode l1 , ListNode l2 ){
if( l1 == null ){
return l2;
}
if( l2 == null ){
return l1;
}
if( l1.val < l2.val ){
l1.next = merge( l1.next , l2 );
return l1;
}
l2.next = merge( l1 , l2.next );
return l2;
}
}
複製代碼
解題思路: 題目要求時間複雜度nlogn ,則須要使用快排或者歸併排序 , 由於是鏈表 , 能夠採用歸併 , 對鏈表進行對半短鏈 ,斷到單節點 , 而後進行歸併 ,最後返回code