1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| public ListNode sortInList (ListNode head) { if (head == null || head.next == null) { return head; }
return mergeSort(head); }
public ListNode mergeSort(ListNode head) { if (head.next == null) { return head; }
ListNode slow = head, fast = head, pre = null; while (fast != null && fast.next != null) { pre = slow; slow = slow.next; fast = fast.next.next; } pre.next = null; ListNode left = mergeSort(head); ListNode right = mergeSort(slow); return merge(left, right); } public ListNode merge(ListNode left, ListNode right) { ListNode dummy = new ListNode(-1); 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; } if (left != null) { cur.next = left; } if (right != null) { cur.next = right; } return dummy.next; }
|