在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3 输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0 输出: -1->0->3->4->5
没有看到nlogn时间复杂度,想起用归并排序。证明对归并排序和快速排序不熟悉。
同时,即归并排序,对链表进行排序,递归的深入,有点复杂
代码:
/**
* 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 a =head,b = head.next;
while((b!=null)&&(b.next!=null)){
head = head.next;
b = (b.next).next;
}
b = head.next;
head.next = null;
return merge(sortList(a),sortList(b));
}
public ListNode merge(ListNode a,ListNode b){
ListNode dummy = new ListNode(0);
ListNode head = dummy,c= head;
while((a!=null) && (b!=null)){
if(a.val<b.val){
c.next = a;
c = a;
a = a.next;
}else{
c.next = b;
c = b;
b = b.next;
}
}
c.next = (a==null)?b:a;
return head.next;
}
}