import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 the head node * @return ListNode类 */ public ListNode sortInList (ListNode head) { // write code here if (head == null || head.next == null) { return head; } // 寻找中心节点 ListNode slow = head; for (ListNode fast = head; fast.next != null && fast.next.next != null; fast = fast.next.next) { slow = slow.next; } ListNode temp = slow.next; slow.next = null; // 递归两边 ListNode left = sortInList(head); ListNode right = sortInList(temp); // 合并两个有序列表 ListNode dummy = new ListNode(0); ListNode cur = dummy; while (left != null && right != null) { if (left.val <= right.val) { cur.next = left; left = left.next; } else { cur.next = right; right = right.next; } cur = cur.next; } cur.next = left == null ? right : left; return dummy.next; } }