1、题目
给你链表的头结点 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
2、解题思路
(1)解决方案一:递归;(每次都找到中间节点拆成两半,这样就是log(n)次调用);
对于单次调用来说,找到中间节点拆分两半,然后返回两半合并之后的头节点;
然后对于递归公式:左边要进行调用返回左边的头节点,右边要进行调用返回右边的头节点
(2)解决方案二:归并;一二排,三四排,五六排;排完之后再进行二次合并,一次从底层汇总成最顶层;
3、java代码
这个是递归的代码;
public ListNode sortList1(ListNode head) {
//终止条件
if (head==null||head.next==null) return head;
//递归公式
//找到中间节点(快慢指针),并拆分成两截
ListNode low=head,fast=head;
while(fast.next!=null && fast.next.next!=null){
fast=fast.next.next;
low=low.next;
}
ListNode mid=low.next;
low.next=null;
ListNode lefthead=sortList1(head);
ListNode righthead=sortList1(mid);
//合并
return mergeTwoLists(lefthead,righthead);
}
//合并两个链表的方法
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
//判空
if (l1==null) return l2;
if (l2==null) return l1;
//新增哨兵节点
ListNode dummyNode=new ListNode(-1);
ListNode pre=dummyNode;
//比较元素,找到next;然后接着进行判断
ListNode cur1=l1;
ListNode cur2=l2;
while(cur1!=null &&cur2!=null){
if(cur1.val<=cur2.val){
pre.next=cur1;
pre=cur1;
cur1=cur1.next;
}else{
pre.next=cur2;
pre=cur2;
cur2=cur2.next;
}
}
if(cur1==null) pre.next=cur2;
if(cur2==null) pre.next=cur1;
//返回头节点
return dummyNode.next;
}