给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
需求
- 升序排列
实现
- 想不想用sort直接排序,哈哈
代码
class Solution {
public ListNode sortList(ListNode head) {
// 判断head是否为空或者head的下一个节点是否为空,如果为空则返回head
if (head == null || head.next == null) return head;
// 使用快慢指针找到链表中点,将链表拆分为两半
ListNode slow = head;
// 重点:解决偶数个节点时,找到链表中点的前一个节点
ListNode fast = head.next;
while (fast != null&& fast.next != null) {
// 快慢指针移动
slow = slow.next;
fast = fast.next.next;
}
// 取得中点
ListNode mid = slow.next;
// 断开链表
slow.next = null;
// 递归排序左右两半,然后合并
ListNode left = sortList(head);
ListNode right = sortList(mid);
return merge(left, right);
}
// 定义合并两个有序链表的函数
private ListNode merge(ListNode l1,ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode curr = dummy;
while (l1 != null&& l2 != null) {
if(l1.val < l2.val) {
curr.next = l1;
l1 = l1.next;
} else {
curr.next = l2;
l2 = l2.next;
}
curr = curr.next;
}
curr.next = (l1 != null) ? l1 : l2;
return dummy.next;
}
}
