Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3 Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0 Output: -1->0->3->4->5
方法1:(这个算法笔记直接,我就用了平时一种比较常见的方法,官方的方法比较难想到,就不推荐了)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
ListNode p=new ListNode(0);
ListNode newHead=p;
List<Integer> list=new ArrayList<>();
while(head!=null){
list.add(head.val);
head=head.next;
}
Collections.sort(list);
for(int ele:list){
p.next=new ListNode(ele);
p=p.next;
}
return newHead.next;
}
}
时间复杂度:O(n.logn)
空间复杂度: