148.排序链表
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
进阶:
- 你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?
示例 1:
输入:head = [4,2,1,3]
输出:[1,2,3,4]
示例 2:
输入:head = [-1,5,3,4,0]
输出:[-1,0,3,4,5]
示例 3:
输入:head = []
输出:[]
提示:
- 链表中节点的数目在范围 [0, 5 * 104] 内
- -105 <= Node.val <= 105
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法一:暴力法
/**
* 执行用时: 15 ms
* 内存消耗: 46.2 MB
**/
public class SortList {
public ListNode sortList(ListNode head) {
ListNode cur = head;
List<Integer> list = new ArrayList<Integer>();
while (cur != null) {
list.add(cur.val);
cur = cur.next;
}
Collections.sort(list);
cur = head;
for (int i = 0; i < list.size(); i++) {
cur.val = list.get(i);
cur = cur.next;
}
return head;
}
}
方法二:递归的归并排序
/**
* 执行用时: 15 ms
* 内存消耗: 46.2 MB
**/
public class SortList {
public ListNode sortList(ListNode head) {
ListNode dummyHead=new ListNode(0);
dummyHead.next=head;
ListNode p=head;
int length=0;
while(p!=null){
length++;
p=p.next;
}
if(head==null||head.next==null)
return head;
//求当前链表中点
ListNode fast=head.next;
ListNode slow=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
}
//切割并递归排序左右链表
ListNode temp=slow.next;
slow.next=null;
ListNode left=sortList(head);
ListNode right=sortList(temp);
//合并链表
ListNode h=new ListNode(0);
ListNode res=h;
while(left!=null&&right!=null){
if(left.val<right.val){
h.next=left;
left=left.next;
}else{
h.next=right;
right=right.next;
}
h=h.next;
}
h.next=left!=null?left:right;
return res.next;
}
}