难度中等1522
给你链表的头结点
head
,请将其按 升序 排列并返回 排序后的链表 。示例 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
使用归并排序
- 全部代码
/**
* 排序链表
* @author happy
* 给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表
*/
public class Num148_sortList {
public ListNode sortList(ListNode head) {
//链表为空/只有一个节点,不用排序
if (head == null || head.next == null ){
return head;
}
//mid是链表的中间节点
ListNode mid = getMidNode(head);
//要先给mid.next一个引用,然后再把链表从中间断开
ListNode right = sortList(mid.next);
mid.next = null;
ListNode left = sortList(head);
return merge(left,right);
}
private ListNode merge(ListNode left, ListNode right) {
ListNode dummyHead = new ListNode(0);
ListNode node = dummyHead;
while (left != null && right != null) {
if (left.val <= right.val) {
node.next = left;
left = left.next;
} else {
node.next = right;
right = right.next;
}
node = node.next;
}
if (left != null) {
node.next = left;
}
if (right != null) {
node.next = right;
}
return dummyHead.next;
}
public ListNode getMidNode(ListNode head) {
ListNode slow = head;
ListNode fast = head.next;
while (fast.next != null && fast.next.next != null){
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
}