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
| class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode mid = splitMid(head);
ListNode left = sortList(head);
ListNode right = sortList(mid);
return merge(left, right);
}
private ListNode splitMid(ListNode head) {
ListNode slow = head, fast = head, prev = null;
while (fast != null && fast.next != null) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = null;
return slow;
}
private ListNode merge(ListNode a, ListNode b) {
ListNode dummy = new ListNode(0), p = dummy;
while (a != null && b != null) {
if (a.val <= b.val) {
p.next = a;
a = a.next;
} else {
p.next = b;
b = b.next;
}
p = p.next;
}
p.next = (a != null) ? a : b;
return dummy.next;
}
}
|