题目
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
示例 1:
输入:head = [4,2,1,3]
输出:[1,2,3,4]
解
class Solution {public ListNode sortList(ListNode head) {if (head == null || head.next == null) {return head;}ListNode dummy = new ListNode(0);dummy.next = head;ListNode slow = dummy;ListNode fast = head;while (fast != null) {slow = slow.next;fast = fast.next;if (fast != null) {fast = fast.next;}}ListNode head2 = slow.next;slow.next = null;ListNode left = sortList(head);ListNode right = sortList(head2);return merge(left, right);}public ListNode merge(ListNode left, ListNode right) {ListNode result = new ListNode(0);ListNode p1 = result;while (left != null && right != null) {if (left.val <= right.val) {p1.next = left;left = left.next;} else {p1.next = right;right = right.next;}p1 = p1.next;}p1.next = left == null ? right : left;return result.next;}
}