问题描述
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
除了下面的代码实现,当然也可以考虑链表快排
import java.util.Collections;
import java.util.ArrayList;
/**
* 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(null == head){
return null;
}
List<Integer> tmp = new ArrayList<Integer>();
while(null != head){
tmp.add(head.val);
head = head.next;
}
Collections.sort(tmp);
ListNode root = new ListNode(-1);
ListNode cur = root;
for(int i = 0; i < tmp.size(); i++){
cur.next = new ListNode(tmp.get(i));
cur = cur.next;
}
return root.next;
}
}