-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy path1.java
60 lines (56 loc) · 1.45 KB
/
1.java
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode mid = split(head);
ListNode left = sortList(head);
ListNode right = sortList(mid);
return merge(left, right);
}
ListNode split(ListNode head) {
ListNode fast = head;
ListNode slow = head;
ListNode prev = null;
while (fast != null && fast.next != null) {
fast = fast.next.next;
prev = slow;
slow = slow.next;
}
prev.next = null;
return slow;
}
ListNode head;
ListNode tail;
ListNode merge(ListNode left, ListNode right) {
head = null;
tail = null;
ListNode q1 = left;
ListNode q2 = right;
while (q1 != null || q2 != null) {
if (q1 == null) {
append(q2);
q2 = q2.next;
} else if (q2 == null) {
append(q1);
q1 = q1.next;
} else if (q1.val < q2.val) {
append(q1);
q1 = q1.next;
} else {
append(q2);
q2 = q2.next;
}
}
return head;
}
void append(ListNode node) {
if (head == null) {
head = node;
tail = node;
} else {
tail.next = node;
tail = node;
}
}
}